[英]How can I group by a distinct list?
我试图按数据库中每个不同的标签对Post
序列进行分组。
public class Post
{
public string Title { get; set; }
public IEnumerable<string> Tags { get; set; }
public static IEnumerable<Post> SeedPosts()
{
yield return new Post { Title = "Foo", Tags = new[] { "Code" } };
yield return new Post { Title = "Foo1", Tags = new[] { "Code", "Productivity" } };
yield return new Post { Title = "Foo2", Tags = new[] { "Miscellaneous" } };
}
}
我想获取SeedPosts
的结果, SeedPosts
以下输出生成到控制台应用程序
Code
Foo
Foo1
Productivity
Foo1
Miscellaneous
Foo2
我很沮丧,但是我将尝试向您展示到目前为止我已经尝试过的内容。
我需要Key
的类型为string
但是当我这样做时
posts.GroupBy(post => post.Tags);
密钥是IEnumerable<string>
类型的。 我知道我正在按IEnumerable<string>
分组,因此密钥是IEnuemrable<string>
,但是无论如何我通常都会卡住。
尝试这个:
posts
.SelectMany(p => p.Tags.Select(t => new {Tag = t, Post = p}))
.GroupBy(_ => _.Tag)
.ToDictionary(_ => _.Key, _ => _.Select(p => p.Post.Title).ToArray());
将列表展平到新列表或同一列表上
var posts = new List<Post>();
posts.Add(new Post { Title = "Foo", Tags = new[] { "Code" } } );
posts.Add(new Post { Title = "Foo1", Tags = new[] { "Code", "Productivity" } });
posts.Add(new Post { Title = "Foo2", Tags = new[] { "Miscellaneous" } });
var flattendPosts = new List<Post>();
foreach (var post in posts)
{
var tags = post.Tags.Select(tag => tag);
for (int i = 0; i < tags.Count(); i++)
{
flattendPosts.Add(new Post { Title = post.Title, Tag = post.Tags[i] });
}
}
flattendPosts.GroupBy(post => post.Tags);
如果您想要的只是将其输出到控制台,则您实际上并不需要Dictionary
:
var posts = Post.SeedPosts();
var tagGroups = posts
.SelectMany(p => p.Tags, (post, tag) => new{Tag = tag, post.Title})
.GroupBy(pair => pair.Tag);
foreach (var tagGroup in tagGroups)
{
Console.WriteLine(tagGroup.Key);
foreach (var pair in tagGroup)
{
Console.WriteLine(" " + pair.Title);
}
}
Console.ReadKey();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.