使用 linq 对结果进行分组



我有一些问题,不知道该怎么办,有人可以帮我吗?我有一张这样的表:

ID   Name   Produkt    Comment   aa    bb
1    Mike   AA         YY        x
1    Mike   AA         YY              x

我想与linq分组的结果就像迈克一样,但只是在一行中

1   Mike   AA          YY        x     x

我的代码:

var results = from t1 in table.AsEnumerable()
                      join tb2 in table2.AsEnumerable()
                      on t1.Field<string>("Name") equals tb2.Field<string>("Name") into prodGroup
                      from table4 in prodGroup.DefaultIfEmpty()
                      select new
                      {
                          ID = t1.Field<Int32?>("ID"),
                          Name = t1.Field<String>("Name"),
                          Produkt = t1.Field<String>("Produkt"),
                          Attribute = t1.Field<String>("Attribute"),
                          Comment = table4 != null ? table4.Field<String>("Comment") : null,
                      };
foreach (var r in results)
{
    var productIndex = result.Columns.IndexOf(r.Attribute);
    var vals = new List<object>() { r.ID, r.Name, r.Produkt, r.Comment };
    for (int i = 4; i < result.Columns.Count; i++)
    {
        if (i == productIndex)
        {
            vals.Add(true);
        }
        else
        {
            vals.Add(false);
        }
    }
    result.LoadDataRow(vals.ToArray(), true);
}

试试这个:

var result = from t1 in table.AsEnumerable()
                group t1 by t1.Name into t1group
                select new
                {
                    Name = t1group.FirstOrDefault().Name
                    ,ID = t1group.FirstOrDefault().ID
                    ,Product = t1group.FirstOrDefault().Product
                    ,Comment = t1group.FirstOrDefault().Comment
                    ,aa = (t1group.Select(x => x.aa??"" + x.bb??"")).Aggregate((a, b) => (a + ", " + b))
                };

相关内容

  • 没有找到相关文章

最新更新