c#查找最佳匹配元素/简化列表查询
本文关键字:列表 查询 元素 查找 最佳 | 更新日期: 2023-09-27 18:07:57
我问自己怎样才能简化这样的事情
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提供了一个解决方案,但我无法找到它:)
谢谢。
从技术上讲,您可以将当前代码简化为
pulic MyObject FindBestMatching(int Prop1Value, int Prop2Value, int Prop3Value) {
return
myList.Find(x => x.Prop1 == Prop1Value && x.Prop2 == Prop2Value && x.Prop3 == Prop3Value)
?? myList.Find(x => x.Prop1 == Prop1Value && x.Prop2 == Prop2Value)
?? myList.Find(x => x.Prop1 == Prop1Value);
}
但是做Find
(扫描整个列表)可能是一个昂贵的操作,如果这是你的情况,你可以在一个循环中找到最佳匹配:
public MyObject FindBestMatching(int Prop1Value, int Prop2Value, int Prop3Value) {
MyObject result1 = null;
MyObject result2 = null;
foreach (MyObject item in myList) {
if (item.Prop1 == Prop1Value) {
result1 = item;
if (item.Prop2 == Prop2Value) {
result2 = item;
if (item.Prop3 == Prop3Value)
return item;
}
}
}
return result2 ?? result1;
}
试试这个:
public MyObject FindBestMatching(int Prop1Value, int Prop2Value, int Prop3Value)
{
return myList.FirstOrDefault(x => (x.Prop1 == Prop1Value && x.Prop2 == Prop2Value && x.Prop3 == Prop3Value)
|| (x.Prop1 == Prop1Value && x.Prop2 == Prop2Value)
|| (x => x.Prop1 == Prop1Value));
}