GroupBy从IEnumerable对象列表中删除重复项 [英] GroupBy to remove duplicates from IEnumerable list of objects

查看:70
本文介绍了GroupBy从IEnumerable对象列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重复名称的列表,我想获得没有重复名称的列表.

I have a list of duplicate names and I want to get the list without the duplicates.

 CSVCategories = from line in File.ReadAllLines(path).Skip(1)
                            let columns = line.Split(',')
                            select new Category
                            {
                                Name = columns[9]
                            };

            var results = CSVCategories.GroupBy(x => x.Name)
                         .Select(g => g.FirstOrDefault())
                         .ToList();

我尝试使用以下循环查看元素并进行调试,但它仍会从列表中返回重复项,包括空值的空字符串:

I try to look at the elements and debug using the following loop, but it still returns the duplicates from the list including empty strings for null values:

foreach(var item in results)
{
    Console.WriteLine(item.Name);
}

推荐答案

我注意到,results变量将我带回了一个包含重复项的列表,但只是大小写不同.

I noticed that the results variable brought me back a list containing duplicates, but only that were different in their casing.

例如我的原始列表CSVCategories中包含以下元素:["Home","home"," EmptyString ","home","Town","Town","Park"]

E.g. My original list CSVCategories contained the elements: ["Home", "home", "EmptyString", "home", "Town", "Town", "Park"]

在使用GroupBy进行重复数据删除时,results查询返回了["Home","home"," EmptyString ","Town","Park"],因此可以正常工作.保留为空的值以及具有不同大小写的值.

When de-duplicating with GroupBy, the results query returned ["Home", "home", "EmptyString", "Town", "Park"], so it kind of worked. Keeping values that are empty and those that have a different casing.

现在,我需要找到一种方法来删除大小写重复和空字符串.

Now I need to find a way to remove casing duplicates and empty strings.

这篇关于GroupBy从IEnumerable对象列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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