我有一个对象:
public class SiteInfo
{
public string Title { get; set; }
public string URL { get; set; }
public string Type { get; set; }
}
我用来创建列表: var 站点 = 新列表();
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 或其他方法执行此操作。
听起来你想要这样的东西:
// 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结构。
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"}]
}
下面是一个简单的控制台应用程序,可以执行您想要的操作:
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