นี่เป็นเวอร์ชันที่เรียบง่ายของสิ่งที่ฉันกำลังพยายามทำ:
var days = new Dictionary<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));
เนื่องจากไม่มี 'xyz' ในพจนานุกรมเมธอด FirstOrDefault จะไม่ส่งคืนค่าที่ถูกต้อง ฉันต้องการตรวจสอบสถานการณ์นี้ แต่ฉันตระหนักดีว่าฉันไม่สามารถเปรียบเทียบผลลัพธ์กับ "null" ได้เนื่องจาก KeyValuePair เป็นโครงสร้าง รหัสต่อไปนี้ไม่ถูกต้อง:
if (day == null) {
System.Diagnotics.Debug.Write("Couldn't find day of week");
}
เราพยายามรวบรวมโค้ด Visual Studio แสดงข้อผิดพลาดต่อไปนี้:
Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'
ฉันจะตรวจสอบได้อย่างไรว่า FirstOrDefault ส่งคืนค่าที่ถูกต้อง