开发者

group by in LINQ query

I've got a DataTable where i want to perform a GroupBy query on.

year    url      type     id
=============================
        someurl  image    0
2003             date     0
        someurl  image    1
2009             d开发者_开发知识库ate     1

I've managed to group on my id, but I am not able to select the columns "year" and "Url".

This is my query:

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

How can i select the columns year and url?

Thanks in advance.


When you group by in LINQ your group (grp) in your case is an enumerable containing all the entries in a group (data rows in your case). You can then either foreach the entries or use aggregate functions like Max, First, etc. to extract a single value from the enumerable


You can group by multiple values. In your case group by id, year and url Check 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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜