C#不同的List< string>按子串 [英] C# distinct List<string> by substring
问题描述
我想从字符串列表中删除重复项.我通过使用"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"都没关系 如果您改变主意,则必须用新的逻辑替换 但是,如果性能确实很重要,并且要删除的重复项并不重要,则应该使用 Selman的方法建议编写一个自定义 ,那将比我的 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. 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 Result:
it doesn't matter if "1A" or "2A" will be deleted If you change your mind you have to replace 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
这篇关于C#不同的List< string>按子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
g.First()
.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();
List<string> mylist = new List<string>();
List<string> newlist =
mylist.Select(e => e.Substring(1, e.Length - 1)).Distinct().ToList();
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();
Console.Write(string.Join(",", result)); // 1A,1B,3C,4D
g.First()
with the new logic.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();