Linq group by distinct and iterate over it

时间:2013-08-12 09:37:31

标签: linq

我想列出所有已发布帖子的所有类别。但我想只显示一次类别。 Post类有一个道具PostsCategories道具的构造函数。它是一个字符串数组而不是List,我想保持这种方式。

public class Post
{
    public static List<Post> Posts = LoadPosts();
}

public Post()
{
    ID = Guid.NewGuid().ToString();
    Categories = new string[0]; //array, no List<string>
}

这是我的剃刀标记

<ul class="categories">
    @{var cl = Post.Posts.Where(p => p.IsPublished).Select(c => new List<string>(c.Categories));}
    @foreach (var cat in cl.Distinct())
    {
        <li>@cat</li>
    }
</ul>

这给了我输出

  

System.Collections.Generic.List`1 [System.String]

我在Linq中做错了什么,但是我没有足够的经验(或清醒)看到我的错误。

1 个答案:

答案 0 :(得分:3)

您需要的是SelectMany方法:

Post.Posts
   .Where(p => p.IsPublished)  // IEnumerable<Post>
   .SelectMany(c => c.Categories) // IEnumerable<string>
   .Distinct()

看起来很奇怪,但SQL select的真正对应方式不是IEnumerable.Select方法,而是IEnumerable.SelectMany方法,因为它可以“平整”选择的结果,而Select为每个元素创建一个单独的集合,结果为:

Post.Posts
  .Where(p => p.IsPublished)  // IEnumerable<Post>
  .Select(c => c.Categories) // IEnumerable<IEnumerable<string>>
  .Distinct() // does nothing, since all inner IEnumerable<string> 
              // objects are different