【问题标题】:AddRange/concat functionality inside a lambda Select expressionlambda Select 表达式中的 AddRange/concat 功能
【发布时间】:2011-04-24 19:14:58
【问题描述】:
class Foo
{
    int PrimaryItem;
    bool HasOtherItems;
    IEnumerable<int> OtherItems;
}

List<Foo> fooList;

如何获取fooList 中引用的所有项目 ID 的列表?

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();

【问题讨论】:

    标签: c# linq select lambda addrange


    【解决方案1】:

    作为一个细微的变化:

    var items = fooList.Select(i => i.PrimaryItem).Union(
          fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));
    

    这需要PrimaryItem 的集合,并且(其中设置了HasOtherItems)连接OtherItems 的组合集合。 Union 确保不同。

    【讨论】:

      【解决方案2】:

      使用SelectMany 并让它返回PrimaryItemOtherItems 的串联列表(如果它们存在):

      var result = fooList
          .SelectMany(f => (new[] { f.PrimaryItem })
              .Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
          .Distinct();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-18
        • 2023-03-04
        • 2016-12-19
        • 2021-04-02
        • 2010-09-11
        • 2014-06-21
        • 1970-01-01
        相关资源
        最近更新 更多