Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

c# - Group List of Objects based on Property using Linq?

I have an object:

public class SiteInfo
        {
            public string Title { get; set; }
            public string URL { get; set; }
            public string Type { get; set; }     
        }

That I am using to create a list: var sites = new List();

        foreach (SPWeb site in web.GetSubwebsForCurrentUser())
        {
            string sitetype = getConfigurationKey(site, "siteType");
            //If sites have a site type then add to list
            if (sitetype != "*ERROR*" && sitetype != "*KEYNOTFOUND*")
            {
                SiteInfo s = new SiteInfo();
                s.Title = site.Title;
                s.URL = site.Url;
                s.Type = sitetype;

                sites.Add(s);
            }
        }
        //sort list by type
        sites.Sort((x, y) => string.Compare(x.Type, y.Type));

        // serialize and send..    
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        StringBuilder sbJsonResults = new StringBuilder();
        serializer.Serialize(sites, sbJsonResults);
etc.....

However what I would like to do is group the sites by Type prior to serializing them. Is this possible using LINQ or some other method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want something like:

// No need to sort sites first
var grouped = sites.OrderBy(x => x.Type)
                   .GroupBy(x => x.Type);

Then just serialize grouped. However, I don't know quite what an IGrouping will look like in JSON... and the type will be present in each case. You may want something like:

var grouped = sites.OrderBy(x => x.Type)
                   .GroupBy(x => x.Type)
                   .Select(g => new { Type = g.Key,
                                      Sites = g.Select(site => new {
                                                           site.Title,
                                                           site.URL
                                                       } });

I think that would give you a nicer JSON structure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...