【问题标题】:How to group by 2 items of a list into another list如何将列表的 2 项分组到另一个列表中
【发布时间】:2019-08-20 16:35:44
【问题描述】:

至于这个例子:

Get a list of distinct values in List

这演示了如何根据 1 个项目获取不同的列表。

您如何获得包含 2 项内容的不同列表。说出作者和标题。

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

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

答案是:

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

【问题讨论】:

  • Notes.Select(x => new string[] {x.Author,x.Title}).Distinct();
  • 你是说x.Author,x.Title吗?
  • 我更正了代码
  • 谢谢。你能把它作为答案,这样它就会关闭吗?

标签: c# linq


【解决方案1】:

正如 jdweng 在 cmets 中建议的那样,您可以这样做:

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

这将返回一个IEnumerable&lt;string[]&gt;

另一种选择是创建一个类以供选择:

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&lt;NoteSummary&gt;

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

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

返回IEnumerable&lt;Note&gt;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2022-11-12
  • 2017-11-18
  • 2021-08-18
  • 2019-06-22
相关资源
最近更新 更多