使用Linq基于属性的对象组列表?

时间:2013-02-01 19:59:22

标签: c# linq list

我有一个对象:

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

        }

我用来创建一个列表:  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或其他方法。

3 个答案:

答案 0 :(得分:22)

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

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

然后只序列化grouped。但是,我不知道JSON中的IGrouping会是什么样的......并且每种情况下都会出现类型。您可能想要类似的内容:

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结构。

答案 1 :(得分:2)

var sites = new List<SiteInfo>()
{
    new SiteInfo(){Title="1",Type="a",URL="http://aaaa"},
    new SiteInfo(){Title="2",Type="b",URL="http://bbbb"},
    new SiteInfo(){Title="3",Type="a",URL="http://aaaa"},
    new SiteInfo(){Title="4",Type="b",URL="http://bbb"},
};

var json = new JavaScriptSerializer().Serialize(sites.GroupBy(s => s.Type));

会产生

[
    [{"Title":"1","URL":"http://aaaa","Type":"a"},{"Title":"3","URL":"http://aaaa","Type":"a"}],
    [{"Title":"2","URL":"http://bbbb","Type":"b"},{"Title":"4","URL":"http://bbb","Type":"b"}]
]

var json = new JavaScriptSerializer().Serialize(sites.GroupBy(s => s.Type)
                                                      .ToDictionary(x=>x.Key,x=>x));

会产生

{
    "a":[{"Title":"1","URL":"http://aaaa","Type":"a"},{"Title":"3","URL":"http://aaaa","Type":"a"}],
    "b":[{"Title":"2","URL":"http://bbbb","Type":"b"},{"Title":"4","URL":"http://bbb","Type":"b"}]
}

答案 2 :(得分:1)

这是一个简单的控制台应用程序,可以满足您的需求:

static void Main(string[] args)
{
    List<SiteInfo> sites = new List<SiteInfo>()
    {
        new SiteInfo() { Title = "Site A", Type = "Whatever 2" },
        new SiteInfo() { Title = "Site B", Type = "Whatever 1" },
        new SiteInfo() { Title = "Site C", Type = "Whatever 1" },
        new SiteInfo() { Title = "Site D", Type = "Whatever 3" },
        new SiteInfo() { Title = "Site E", Type = "Whatever 3" }
    };

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

    foreach (var siteTypeGroup in sitesGroupedByType.OrderBy(g => g.Type))
    {
        foreach(var site in siteTypeGroup.Sites)
        {
            Console.WriteLine(string.Format("Type => {0}, Title => {1}",
                              siteTypeGroup.Type, site.Title));
        }
    }

    Console.ReadKey();
}

输出:

Type => Whatever 1, Title => Site B
Type => Whatever 1, Title => Site C
Type => Whatever 2, Title => Site A
Type => Whatever 3, Title => Site D
Type => Whatever 3, Title => Site E