2016-09-21 25 views
1

我问自己,我怎么能简化像这样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提供了一个解决方案,但我不能找到它:)

谢谢。

+2

你为什么觉得有一个更容易的方法?您可以使用'FirstOrDefault',但无论如何您都需要空值检查。我认为你的解决方案已经是最好的解决方案了,至少它是可读和不可调整的,并且*这是*真正重要的 - 至少对我来说。 – HimBromBeere

回答

1

从技术上讲,可以简化目前的代码到

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(scaning的整个列表)可以是一个代价高昂的操作,如果它是你的例如,您只能在一个循环中找到最佳匹配:

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; 
    } 
+0

谢谢你的答案。一个提示:我认为if(x.Prop1 == Prop1Value)后面有一个{丢失了 – ErWu

+0

啊,你知道了:) – ErWu

+0

@ErWu:你说得对,它应该是'''if'后面(item.Prop1 = = Prop1Value)'。我对这个错字感到抱歉。我编辑了答案 –

0

试试这个:

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)); 
} 
+0

这不起作用。它只是发现其中一个条件为真的第一个元素 – ErWu