如何将一个列表的2个项目分组到另一个列表中 [英] How to group by 2 items of a list into another list

查看:82
本文介绍了如何将一个列表的2个项目分组到另一个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此示例:

获取列表中不同值的列表

这演示了如何基于一项获得不同的列表.

This demonstrates how to get a distinct list based on 1 item.

您如何获得两件事情的独特清单.说作者和标题.

How do you get a distinct list of 2 things. Say Author and title.

public class Note
{
    public string Title;
    public string Author;
    public string Text;
}

List<Note> Notes = new List<Note>();

一个答案是:

Notes.Select(x => x.Author).Distinct();

推荐答案

正如jdweng在评论中建议的那样,您可以执行以下操作:

As jdweng suggested in the comments you can do:

Notes.Select(x => new string[] {x.Title, x.Author}).Distinct();

,它将返回一个IEnumerable<string[]>.

另一种选择是创建一个要选择的类:

Another option is to create a class to select into:

public class NoteSummary()
{
    public string Title { get; set; }
    public string Author { get; set; }

    public NoteSummary(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

然后linq变为:

Notes.Select(x => new NoteSummary(x.Title, x.Author)).Distinct();

返回IEnumerable<NoteSummary>.

如果要返回原始Note类/实体的分组集合,则可以使用GroupBy:

If you want to return a grouped collection of the original Note class/entity you can use GroupBy:

Notes
  .GroupBy(g => new { g.Title, g.Author })  // group by fields
  .Select(g => g.First());                  // select first group

返回IEnumerable<Note>.

这篇关于如何将一个列表的2个项目分组到另一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆