C#不同的List< string>按子串 [英] C# distinct List<string> by substring

查看:148
本文介绍了C#不同的List< string>按子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串列表中删除重复项.我通过使用"distinct"来做到这一点,但是在比较时我想忽略第一个字符.

我已经有一个可以删除重复项的工作代码,但是我的代码也删除了每个字符串的第一个字符.

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

List<string> newlist = 
  mylist.Select(e => e.Substring(1, e.Length - 1)).Distinct().ToList();

输入: "1A" ,"1B","2A" ,"3C","4D"

输出: "A","B","C","D"

右输出: "1A","2B","3C","4D"与"1A"或"2A"将被删除无关紧要

我想我已经很接近了,但是..任何输入都将受到高度赞赏!

一如既往,解决方案应尽可能快地工作;)

解决方案

您可以

删除"1A"还是"2A"都没关系

如果您改变主意,则必须用新的逻辑替换g.First().

但是,如果性能确实很重要,并且要删除的重复项并不重要,则应该使用 Selman的方法建议编写一个自定义IEqualityComparer<string>.如果GetHashCode的实现方式类似于:

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

List<string> newlist = 
  mylist.Select(e => e.Substring(1, e.Length - 1)).Distinct().ToList();

,那将比我的GroupBy方法更有效.

return (s.Length < 2 ? s : s.Substring(1)).GetHashCode();

I want to remove duplicates from a list of strings. I do this by using distinct, but i want to ignore the first char when comparing.

I already have a working code that deletes the duplicates, but my code also delete the first char of every string.

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

List<string> newlist = 
  mylist.Select(e => e.Substring(1, e.Length - 1)).Distinct().ToList();

Input: "1A","1B","2A","3C","4D"

Output: "A","B","C","D"

Right Output: "1A","2B","3C","4D" it doesn't matter if "1A" or "2A" will be deleted

I guess I am pretty close but.... any input is highly appreciated!

As always a solution should work as fast as possible ;)

解决方案

You can GroupBy all but the first character and take the first of every group:

List<string> result= mylist.GroupBy(s => s.Length < 2 ? s : s.Substring(1))
                           .Select(g => g.First())
                           .ToList();

Result:

Console.Write(string.Join(",", result)); // 1A,1B,3C,4D

it doesn't matter if "1A" or "2A" will be deleted

If you change your mind you have to replace g.First() with the new logic.

However, if performance really matters and it is never important which duplicate you want to delete you should prefer Selman's approach which suggests to write a custom IEqualityComparer<string>. That will be more efficient than my GroupBy approach if it's GetHashCode is implemented like:

return (s.Length < 2 ? s : s.Substring(1)).GetHashCode();

这篇关于C#不同的List&lt; string&gt;按子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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