C#查找最佳匹配元素/简化查询到列表

时间:2016-09-21 08:37:26

标签: c# linq

我问自己如何简化这样的事情

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 个答案:

答案 0 :(得分: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(扫描整个列表)可能是一项代价高昂的操作,如果是这种情况,您只能在一个循环中找到最佳匹配:

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

答案 1 :(得分: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));
}