按多列分组

Group By Multiple Columns

提问人:Sreedhar 提问时间:5/11/2009 最后编辑:John SmithSreedhar 更新时间:10/25/2023 访问量:776950

问:

如何在 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
c# 。网 LINQ 分组依据 骨料

评论


答:

1386赞 leppie 5/11/2009 #1

使用匿名类型。

例如

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

评论

37赞 Chris 8/6/2013
如果您不熟悉使用匿名类型进行分组,那么在此示例中使用“new”关键字可以发挥神奇的作用。
536赞 Sreedhar 5/11/2009 #2

好的,得到这个:

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();
921赞 Mo0gles 2/7/2012 #3

程序示例:

.GroupBy(x => new { x.Column1, x.Column2 })
10赞 Chris Smith 11/13/2013 #4

尽管此问题询问的是按类属性分组,但如果要针对 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);
23赞 Jay Bienvenu 12/30/2015 #5

还可以将 Tuple<> 用于强类型分组。

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),
}
202赞 Milan 12/30/2015 #6

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

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

同样,您可以添加 Column3、Column4 等。

2赞 Arindam 5/16/2016 #7
var Results= query.GroupBy(f => new { /* add members here */  });
51赞 user2897701 3/14/2017 #8

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

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

.GroupBy(x => (x.Column1, x.Column2))
0赞 Kai Hartmann 5/19/2017 #9
.GroupBy(x => x.Column1 + " " + x.Column2)
1赞 John 10/23/2017 #10

group x by new { x.Col, x.Col}

1赞 Let's Enkindle 12/27/2017 #11

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

3赞 Ogglas 4/27/2018 #12

需要注意的一点是,您需要为 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;
}
44赞 AlbertK 2/9/2019 #13

C# 7.1 或更高版本,使用 and(目前它仅适用于需要表达式树时不支持,例如 .Github 问题):TuplesInferred tuple element nameslinq to objectssomeIQueryable.GroupBy(...)

// declarative query syntax
var result = 
    from x in inMemoryTable
    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 = inMemoryTable.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) });
0赞 Dani 5/6/2020 #14

对于 VBanonymous/lambda

query.GroupBy(Function(x) New With {Key x.Field1, Key x.Field2, Key x.FieldN })
-1赞 osexpert 10/24/2023 #15

其他答案适用于固定\静态列,您可以在编码时知道要对哪些内容进行分组。但是,如果在程序运行之前不知道要按哪列或多少列进行分组,则可以执行以下操作:

public class GroupingKey<T> : IEquatable<GroupingKey<T>>
{
    public T[] Groups { get; init; }
    static EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;

    public GroupingKey(T[] groups)
    {
        Groups = groups;
    }

    public override int GetHashCode()
    {
        var hc = new HashCode();
        foreach (var g in Groups)
            hc.Add(g);
        return hc.ToHashCode();
    }

    public override bool Equals(object? other)
    {
        return Equals(other as GroupingKey<T>);
    }

    public bool Equals(GroupingKey<T>? other)
    {
        if (other == null)
            return false;

        if (ReferenceEquals(this, other))
            return true;

        if (Groups.Length != other.Groups.Length)
            return false;

        for (int i = 0; i < Groups.Length; i++)
        {
            if (!equalityComparer.Equals(Groups[i], other.Groups[i]))
                return false;
        }

        return true;
    }

    public override string ToString()
    {
        string[] array = new string[Groups.Length];
        for (int i = 0; i < Groups.Length; i++)
            array[i] = $"Group{i} = {Groups[i]}";

        return $"{{ {string.Join(", ", array)} }}";
    }
}

示例使用:

public void GroupByAnyColumns(List<string[]> rows, List<int> groupByColumnIndexes)
{
    var grouped = rows.GroupBy(row => new GroupingKey<string>(groupByColumnIndexes.Select(colIdx => row[colIdx]).ToArray()));
}