使用linq对结果进行分组

时间:2012-10-01 14:56:42

标签: c# linq left-join linq-group

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

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);
}

1 个答案:

答案 0 :(得分:1)

试试这个:

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))
                };