Select A 或 B 使用 Linq

Select A or B using Linq

我有以下代码:

public interface ISomeInterface
{ 
  string Id { get; set; }
}

public class ObjectOne : ISomeInterface
{
  public string Id;
  // Other properties... 
}

public class ObjectTwo : ISomeInterface
{
  public string Id;
  // Other properties...
}

还有这个:

public class MyModel
{
  public List<ObjectOne> ObjectOneCollection;
  public List<ObjectTwo> ObjectTwoCollection;

  public ISomeInterface GetMatching(string key)
  {
    ISomeInterface result;

    result = from ISomeInterface a in ObjectOneCollection
             from ISomeInterface b in ObjectTwoCollection
             where a.Id == key || 
                   b.Id == key
             select new { a, b }; // This is where I'm having trouble.

    return result;
  } 

  // Other methods
}

我基本上是在 LINQ 查询中尝试 select ab,以先到者为准。我该怎么做?

(我知道有很多方法可以做到这一点,例如首先尝试获取 a 并进行空值检查,等等 b。这会产生一些丑陋的代码。我也了解如何使用 Concat 合并两个集合。)

看起来您只是想找到第一个匹配的,最好的选择应该是 Concat() 集合和 return 第一个匹配:

ObjectOneCollection.Cast<ISomeInterface>()
  .Concat(ObjectTwoCollection.Cast<ISomeInterface>())
  .FirstOrDefault(a => a.Key == key);