且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个列表的2个项目分组到另一个列表中

更新时间:2023-01-08 16:28:17

正如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>.