我正在尝试按数据库中的每个 distinct 标记对Post
s序列进行分组。
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
的结果并将以下输出生成到控制台应用程序
Code
Foo
Foo1
Productivity
Foo1
Miscellaneous
Foo2
我很难过,但我会尝试向你展示我到目前为止所尝试的内容。
我需要Key
为string
类型,但是当我这样做时
posts.GroupBy(post => post.Tags);
密钥是IEnumerable<string>
类型的密钥。我知道我正在按IEnumerable<string>
分组,所以关键是IEnuemrable<string>
,但我总是被卡住了。
答案 0 :(得分:2)
试试这个:
posts
.SelectMany(p => p.Tags.Select(t => new {Tag = t, Post = p}))
.GroupBy(_ => _.Tag)
.ToDictionary(_ => _.Key, _ => _.Select(p => p.Post.Title).ToArray());
答案 1 :(得分:2)
将列表展平为新列表或同一列表
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);
答案 2 :(得分:1)
如果你想要的只是将它输出到控制台,你真的不需要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();