c# - 如何将这些类似的 linq 查询合并为一个?

标签 c# linq

这可能是一个基本的 LINQ 问题。我需要选择一个对象,如果它为空,则选择另一个。我通过以下方式使用 linq to objects,我知道可以更快、更好、更清洁地完成...

    public Attrib DetermineAttribution(Data data)
    {

        var one = from c in data.actions
                           where c.actionType == Action.ActionTypeOne
                           select new Attrib 
                                      {
                                          id = c.id,
                                          name = c.name
                                      };
        if( one.Count() > 0)
            return one.First();

        var two = from c in data.actions
                  where c.actionType == Action.ActionTypeTwo
                  select new Attrib
                             {
                                 id = c.id,
                                 name = c.name
                             };
        if (two.Count() > 0 )
            return two.First();

  }

这两个 linq 操作仅在 where 子句上有所不同,我知道有一种方法可以将它们结合起来。如有任何想法,我们将不胜感激。

最佳答案

我认为这个解决方案简单高效:

public Attrib DetermineAttribution(Data data)
{
    var c = data.actions.FirstOrDefault(c => c.actionType == Action.ActionTypeOne) ??
            data.actions.FirstOrDefault(c => c.actionType == Action.ActionTypeTwo);
    return c != null ? new Attrib { id = c.id, name = c.name } : null;
}

关于c# - 如何将这些类似的 linq 查询合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766585/

相关文章:

c# - 有 {} 运算符吗?

c# - 我应该创建多个 Controller 还是具有多个操作的单个 Controller 来处理更详细的响应?

c# - 我们如何检索 WhereSelectListIterator 的第一项?

c# - SQLite 错误没有这样的列使用 Entity Framework

c# linq-to-sql EF 查询以匹配特定的 JSON 结构

c# - WebForms ASCX 中的 Linq Lambda 支持

c# - 使用 LINQ 获取组的平均值

c# - WIF 是否必须与 ADFS 2.0 集成

c# - 为什么 LINQ .Where(predicate).First() 比 .First(predicate) 快?

c# - ServiceStack:依赖调用