在C#中从List<string>中删除重复项

12

在C#中从列表中删除重复项

我有一个数据读取器来从数据库中读取字符串。

我使用List来聚合从数据库中读取的字符串,但是这些字符串中有重复项。

有人有一种快速的方法可以从C#的通用List中删除重复项吗?

List<string> colorList = new List<string>();

    public class Lists
    {
        static void Main()
        {
            List<string> colorList = new List<string>();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            colorList.Add(variableFromDB.ToString());

                    foreach (string color in colorList)
                    {
                      Response.Write(color.ToString().Trim());
                    }
        }
    }

1
.Distinct() 是什么意思? - Sam
4个回答

53
colorList = colorList.Distinct().ToList();

5
foreach (string color in colorList.Distinct())

4
IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

6
为什么不直接使用 sourceList.GroupBy(x => x.FooName).Select(x => x.First()) - Darren Reid

3

这对于自定义对象不起作用。 - Jamie Nicholl-Shelley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接