按多列分组

时间:2009-05-11 07:24:40

标签: .net linq group-by aggregate

如何在LINQ中执行GroupBy多列

SQL中与此类似的东西:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>

如何将其转换为LINQ:

QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

14 个答案:

答案 0 :(得分:1124)

使用匿名类型。

例如

group x by new { x.Column1, x.Column2 }

答案 1 :(得分:698)

程序样本

.GroupBy(x => new { x.Column1, x.Column2 })

答案 2 :(得分:441)

好的就是:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();

答案 3 :(得分:133)

对于按多列分组,请尝试此操作...

GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new 
{ 
  Key1 = key.Column1,
  Key2 = key.Column2,
  Result = group.ToList() 
});

您可以添加Column3,Column4等。

答案 4 :(得分:23)

从C#7开始,你也可以使用值元组:

group x by (x.Column1, x.Column2)

.GroupBy(x => (x.Column1, x.Column2))

答案 5 :(得分:16)

您还可以使用元组&lt;&gt;对于强类型分组。

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
}

答案 6 :(得分:8)

虽然这个问题是按类属性询问,但是如果要针对ADO对象(如DataTable)按多个列进行分组,则必须将“新”项分配给变量:

EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
                        .Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
                    var Dups = ClientProfiles.AsParallel()
                        .GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
                        .Where(z => z.Count() > 1)
                        .Select(z => z);

答案 7 :(得分:6)

C#7.1或更高版本,使用TuplesInferred tuple element names

// declarative query syntax
var result = 
    from x in table
    group x by (x.Column1, x.Column2) into g
    select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));

// or method syntax
var result2 = table.GroupBy(x => (x.Column1, x.Column2))
    .Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));

C#3或更高版本,使用anonymous types

// declarative query syntax
var result3 = 
    from x in table
    group x by new { x.Column1, x.Column2 } into g
    select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };

// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
    .Select(g => 
      new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });

答案 8 :(得分:4)

var Results= query.GroupBy(f => new { /* add members here */  });

答案 9 :(得分:3)

.GroupBy(x => (x.MaterialID, x.ProductID))

答案 10 :(得分:2)

.GroupBy(x => x.Column1 + " " + x.Column2)

答案 11 :(得分:2)

按新{x.Col,x.Col}分组x

答案 12 :(得分:0)

需要注意的是,您需要为Lambda表达式发送一个对象,并且不能为类使用实例。

示例:

public class Key
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

这将编译,但每个周期将生成一个键

var groupedCycles = cycles.GroupBy(x => new Key
{ 
  Prop1 = x.Column1, 
  Prop2 = x.Column2 
})

如果您不想命名关键属性然后检索它们,您可以这样做。这将GroupBy正确并为您提供关键属性。

var groupedCycles = cycles.GroupBy(x => new 
{ 
  Prop1 = x.Column1, 
  Prop2= x.Column2 
})

foreach (var groupedCycle in groupedCycles)
{
    var key = new Key();
    key.Prop1 = groupedCycle.Key.Prop1;
    key.Prop2 = groupedCycle.Key.Prop2;
}

答案 13 :(得分:0)

对于 VB anonymous / lambda

$ make test
cc    -c -o test.o test.c
cc   -Wl,--no-undefined     test.o   -o test

$ make test_ld
ld   --no-undefined    -o test_ld test.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000