簡體   English   中英

如何按不同的列表分組?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM