在LINQ查询中分组

时间:2011-05-10 09:00:34

标签: c# .net linq group-by

我有一个DataTable,我想在其上执行GroupBy查询。

year    url      type     id
=============================
        someurl  image    0
2003             date     0
        someurl  image    1
2009             date     1

我设法对我的ID进行分组,但我无法选择“年”和“Url”列。

这是我的疑问:

var query = from row in table.AsEnumerable()
            let uri = row["uri"]
            group row by row.Field<int>("id") into grp
            orderby grp.Key
            select new
            {
                ID = grp.Key,
            };

如何选择列年份和网址?

提前致谢。

2 个答案:

答案 0 :(得分:1)

当您在LINQ中分组时,您的组中的组(grp)是一个包含组中所有条目的可枚举(在您的情况下为数据行)。然后,您可以预先输入条目或使用Max,First等聚合函数从可枚举中提取单个值

答案 1 :(得分:0)

您可以按多个值进行分组。在您的案例组中按ID,年份和网址 查看here

    List<WebResource> webResources = new List<WebResource>();
    webResources.Add(new WebResource() { Id = 1, Type = "Image", Url = "url1", Year = 2001 });
    webResources.Add(new WebResource() { Id = 1, Type = "Text", Url = "url1", Year = 2001 });
    webResources.Add(new WebResource() { Id = 3, Type = "Image", Url = "url1", Year = 2001 });
    webResources.Add(new WebResource() { Id = 1, Type = "Text", Url = "url1", Year = 2002 });
    webResources.Add(new WebResource() { Id = 2, Type = "Image", Url = "url1", Year = 2002 });
    webResources.Add(new WebResource() { Id = 3, Type = "Text", Url = "url2", Year = 2002 });
    webResources.Add(new WebResource() { Id = 1, Type = "Image", Url = "url1", Year = 2002 });
    webResources.Add(new WebResource() { Id = 2, Type = "Text", Url = "url2", Year = 2002 });

    var output = webResources.GroupBy(webResource => new {webResource.Id, webResource.Year, webResource.Url })
        .Select(group => new {Key = group.Key, Count = group.Count()});

    foreach (var webResource in output)
    {
        Console.WriteLine("Id: " + webResource.Key.Id +" Url:" + webResource.Key.Url + " Year:" + webResource.Key.Year + "  Count:" + webResource.Count);
    }