使用Linq基于属性的对象分组列表? [英] Group List of Objects based on Property using Linq?

查看:89
本文介绍了使用Linq基于属性的对象分组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象:

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

我正在用来创建列表: var sites = new List();

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.....

但是,我想做的是在对网站进行序列化之前按类型对它们进行分组.使用LINQ或其他方法可以做到这一点吗?

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.

推荐答案

听起来您想要这样的东西:

It sounds like you want something like:

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

然后只需序列化grouped.但是,我不太了解IGrouping在JSON中的样子……并且每种情况下都会显示类型.您可能想要类似的东西:

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

认为,它将为您提供更好的JSON结构.

I think that would give you a nicer JSON structure.

这篇关于使用Linq基于属性的对象分组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆