如何按不同的列表分组?

How can I group by a distinct list?

我试图通过数据库中的每个 distinct 标记对一系列 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 的结果并向控制台应用程序生成以下输出

Code
 Foo
 Foo1
Productivity
  Foo1
Miscellaneous
  Foo2

我完全被难住了,但我会尝试向您展示我到目前为止所做的尝试。

我需要 Keystring 类型,但是当我这样做时

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