代码之家  ›  专栏  ›  技术社区  ›  Slaggg

如何使用Linq的聚合函数C添加到列表中#

  •  9
  • Slaggg  · 技术社区  · 17 年前

    问题是所有聚合示例都使用类型line string或int,它们支持“+”运算符。我希望累加器类型是一个列表,它不支持“+”语义。

    下面是一个简单的例子:

    public class DestinationType
    {
        public DestinationType(int A, int B, int C) { ... }
    }
    
    var set = from item in context.Items
              select new { item.A, item.B, item.C };
    
    var newSet = set.Aggregate( new List<DestinationType>(),
                                (list, item) => list.Add(new DestinationType(item.A, item.B, item.C)) );
    

    问题是这个列表<>。添加返回无效。要聚合的第二个参数的返回类型必须是列表。

    如果我有一个支持“+”类型语义的列表类型,我可以只做第二个参数

    list + item
    

    但是,我找不到任何支持这种类型的集合类型。

    似乎这在Linq中很容易实现。有办法吗?此外,如果我错过了一个完全简单的方法,我也很想了解这一点。谢谢

    5 回复  |  直到 17 年前
        1
  •  28
  •   Dustin Campbell    17 年前

    假设这是LINQ to对象,请尝试。。。

    var newSet = set.Aggregate(new List<DestinationType>(),
                                        (list, item) =>
                                        {
                                            list.Add(new DestinationType(item.A, item.B, item.C));
                                            return list;
                                        });
    
        2
  •  10
  •   Samuel Jack    17 年前

    我想打电话给 Select 与…结合 ToList()

    context.Items
      .Select(item => new DestinationType(item.A, item.B, item.C))
      .ToList();
    
        3
  •  4
  •   Dario    17 年前

    select

    var newSet = set.Select(item => new DestinationType(...)).ToList();
    

    Aggregate fold reduce 结合 元素在一起,在哪里 将函数应用于每个元素。

    前任:

    允许 f 那么是一元函数吗 [a, b, c]. select (f) [f(a), f(b), f(c)] .

    允许 [a,b,c]。 aggregate (f, init) 等于 f(a, f(b, f(c, init))) .

    您在示例中选择的方式在C#中不常见,但在函数式编程中经常使用,其中(链接)列表转换为新列表,而不是更改现有集合:

    reversed = fold (\list element -> element:list) [] [1..10]
    

    如果你真的想用 总数的 ,使用Dustin的解决方案,或者更好地为不可变集合实现基于链表的类型(您甚至可以为该类型指定 operator + ).

        4
  •  3
  •   Talljoe    17 年前
    list.AddRange(context.Items.Select(item => 
      new DestinationType(item.A, item.B, item.C));
    

    我知道它不使用聚合函数,但您可能应该找到更好的示例来学习聚合。

        5
  •  1
  •   Aidamina    15 年前

    除非我遗漏了一些明显的东西,为什么不直接做:

    public class DestinationType
    {
        public DestinationType(int A, int B, int C) { ... }
    }
    
    var newSet = from item in context.Items
        select new DestinationType(item.A, item.B, item.C);