简体   繁体   中英

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.

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

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

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

the key is a of type 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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