简体   繁体   English

如何按不同的列表分组?

[英]How can I group by a distinct list?

I am trying to group a sequence of Post s by each distinct tag in the database. 我试图按数据库中每个不同的标签对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" } };
    }
}

I want to take the result of SeedPosts and produce the following output to a console application 我想获取SeedPosts的结果, SeedPosts以下输出生成到控制台应用程序

Code
 Foo
 Foo1
Productivity
  Foo1
Miscellaneous
  Foo2

I am totally stumped but I will make an attempt to show you what I have tried so far. 我很沮丧,但是我将尝试向您展示到目前为止我已经尝试过的内容。

I need the Key to be of type string but when I do this 我需要Key的类型为string但是当我这样做时

posts.GroupBy(post => post.Tags);

the key is a of type IEnumerable<string> . 密钥是IEnumerable<string>类型的。 I understand that I am grouping by an IEnumerable<string> , and so the key is an IEnuemrable<string> , but I am generally stuck anyway. 我知道我正在按IEnumerable<string>分组,因此密钥是IEnuemrable<string> ,但是无论如何我通常都会卡住。

Try this: 尝试这个:

posts
    .SelectMany(p => p.Tags.Select(t => new {Tag = t, Post = p}))
    .GroupBy(_ => _.Tag)
    .ToDictionary(_ => _.Key, _ => _.Select(p => p.Post.Title).ToArray());

Flatten the list either on a new list or the same one 将列表展平到新列表或同一列表上

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

You don't really need a Dictionary if all you want is outpuuting this to the console: 如果您想要的只是将其输出到控制台,则您实际上并不需要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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM