获取 List 中不同值的列表 [英] Get a list of distinct values in List

查看:30
本文介绍了获取 List 中不同值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,假设我有一个名为 Note 的类,其中包含三个字符串成员变量.

In C#, say I have a class called Note with three string member variables.

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

我有一个 Note 类型的列表:

And I have a list of type Note:

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

获取 Author 列中所有不同值的列表的最简洁方法是什么?

What would be the cleanest way to get a list of all distinct values in the Author column?

我可以遍历列表并将所有不重复的值添加到另一个字符串列表中,但这看起来很脏而且效率低下.我有一种感觉,有一些神奇的 Linq 结构可以在一行中完成此操作,但我一直想不出任何办法.

I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.

推荐答案

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

这将返回一个序列(IEnumerable)Author 值——每个唯一值一个.

This will return a sequence (IEnumerable<string>) of Author values -- one per unique value.

这篇关于获取 List 中不同值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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