无法在 select linq 方法中访问 class 的成员

Cannot access members of a class in the select linq method

static void Main(){

List<Foo> t = new List<Foo>{
            new Foo(){Id=1,Name="A",Value=1},
            new Foo(){Id=2,Name="B",Value=1},
            new Foo(){Id=3,Name="C",Value=1},
            new Foo(){Id=3,Name="D",Value=1}};

var x = t.GroupBy(gp => gp.Id).Select(sel => new Foo {  Id = ,Name=,Value= });

}

public class Foo{
    public string Name { get; set; }
    public int Id { get; set; }
    public int Value { get; set; }
}

var x 中,我想按 ID 对所有 Foo 对象进行分组,并在值字段中获取 SUM。

问题是我似乎无法访问 select 方法中 class 的 members/fields。

谢谢

GroupBy 之后,您 select 不是 IEnumerable<Foo>,而是成群结队。你可能想要:

var x = t.GroupBy(f => f.Id)
    .Select(grp => new Foo {  
        Id = grp.Key, 
        Name = String.Join(",", grp.Select(f => f.Name)),
        Value = grp.Sum(f => f.Value)
    });

我正在使用 String.Join 连接每个 ID 组的所有名称,将值相加。

试试这个方法

var x = t.GroupBy(gp => gp.Name).OrderBy(group => group.Key).Select(group => Tuple.Create (group.Key, group.Count()));