我问自己,我怎么能简化像这样C#查找最佳匹配元素/简化查询列出
var myList = new List<MyObject>
pulic MyObject FindBestMatching(int Prop1Value, int Prop2Value, int Prop3Value)
{
MyObject item = null;
item = myList.Find(x => x.Prop1 == Prop1Value && x.Prop2 == Prop2Value && x.Prop3 == Prop3Value);
if(item != null)
{
return item;
}
item = myList.Find(x => x.Prop1 == Prop1Value && x.Prop2 == Prop2Value);
if(item != null)
{
return item;
}
item = myList.Find(x => x.Prop1 == Prop1Value);
// Doesn't matter if its null
return item;
}
我敢肯定,LINQ提供了一个解决方案,但我不能找到它:)
谢谢。
你为什么觉得有一个更容易的方法?您可以使用'FirstOrDefault',但无论如何您都需要空值检查。我认为你的解决方案已经是最好的解决方案了,至少它是可读和不可调整的,并且*这是*真正重要的 - 至少对我来说。 – HimBromBeere