简体   繁体   English

使列表在不同列表的c#中不同

[英]Making a list distinct in c# of a distinct list

I am making a list distinct which is working. 我正在制作一份有效的清单。 but the issue i have changed all the sting into lower cases values as well. 但问题是我已将所有刺痛变为小例值。 But because i am trying to count the number of occurrence of the distinct value in the original list, to do this i am using nested for loops and counting the value, the problem i am facing is that in some of the stings there is a space at the end. 但是因为我试图计算原始列表中不同值的出现次数,为了做到这一点,我使用嵌套for循环并计算值,我面临的问题是在某些蜇中有一个空格在末尾。 so when comparing the two string they wouldn't match because of the space at the then which would lead the distinct List to have the same two values. 因此,当比较两个字符串时,它们将不匹配,因为当时的空格会导致不同的List具有相同的两个值。 is there any way around this 有没有办法解决

var distinctList = list.Distinct();

You need to Trim() first before do Distinct() 在做Distinct()之前你需要先Trim() Distinct()

var list = new[] {" string", "string "};
var distinctList = list.Select(s => s.Trim()).Distinct();

If you also need to ignore case-sensitive: 如果您还需要忽略区分大小写:

var list = new[] {" String", "string "};
var distinctList = list.Select(s => s.Trim())
                       .Distinct(StringComparer.InvariantCultureIgnoreCase);

If your list contains null , presumably you ignore it, you can easily filter first: 如果您的列表包含null ,可能是您忽略它,则可以先轻松过滤:

var list = new[] {" String", "string ", null};

var distinctList = list.Where(s => !string.IsNullOrEmpty(s))
                       .Select(s => s.Trim())
                       .Distinct(StringComparer.InvariantCultureIgnoreCase);

In case you need to keep null on the result, create an extension method to customize Trim() : 如果您需要在结果上保持null ,请创建一个扩展方法来自定义Trim()

    public static string CusTrim(this string @this)
    {
        return @this == null ? null : @this.Trim();
    }

Then you can call: 然后你可以打电话:

var distinctList = list.Select(s => s.CusTrim())
                       .Distinct(StringComparer.InvariantCultureIgnoreCase);

There's a better way. 还有更好的方法。 First, as Cuong correctly showed, you should be trimming your values to remove leading or trailing spaces. 首先,正如Cuong正确显示的那样,您应该修剪您的值以删除前导或尾随空格。

Second, if you want the number of occurrences of each distinct value, you can group them and count them in the same Linq statement. 其次,如果您想要每个不同值的出现次数,您可以对它们进行分组并在同一Linq语句中对它们进行计数。 It might look something like this (EDIT: you mentioned you had some null values you wanted to keep, which you must take into account when you call methods on your list elements): 它可能看起来像这样(编辑:你提到你有一些你想要保留的空值,当你在列表元素上调用方法时必须考虑到这些值):

var groupedCounts = list.Select(s=>s == null ? s : s.ToLowerInvariant().Trim())
                    .GroupBy(x=>x)
                    .Select(g=>new {g.Key, g.Count()});

The group creates a "Lookup", basically a read-only, keyed collection of IEnumerables where the key is based on the grouping projection (here we just want to compare the string, but you could conceivably also group by the first character or by other means). 该组创建了一个“查找”,基本上是IEnumerables的只读,键控集合,其中键基于分组投影(这里我们只想比较字符串,但您可以想象也可以按第一个字符或其他字符分组)手段)。 Then, the last Select creates an "anonymous type" with two fields, Key and Count (they're auto-named based on the values they get). 然后,最后一个Select创建一个“匿名类型”,其中包含两个字段:Key和Count(它们是根据它们获得的值自动命名的)。

Note that the use of anonymous types is restricted to local scope; 请注意,匿名类型的使用仅限于本地范围; you can't return this collection in a strongly-typed manner because by definition it's not a "strong type". 你不能以强类型的方式返回这个集合,因为根据定义它不是一个“强类型”。 If this list needs to go somewhere else, such as being set to an instance property or returned from your current method, you could create Tuples instead of anonymous class instances, or KeyValuePairs, etc. 如果此列表需要转到其他位置,例如设置为实例属性或从当前方法返回,则可以创建元组而不是匿名类实例,或KeyValuePairs等。

you can filter using linq. 你可以使用linq过滤。

var destinctList = list.Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => x.TrimEnd()).Distinct().ToList();

This will also remove empty strings 这也将删除空字符串

你可以做点什么......

list.Select(i => i.Trim()).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM