简体   繁体   English

从单词序列中返回不同的元素

[英]Return distinct elements from a sequence of words

supposing I have a List with some words like this: 假设我有一个包含这样的单词的列表:

List<string> words = new List<string>{ "apple", "computer", "user", "AppLe", "USer", "photo", "USER" };

and I want to produce a new list like this: 我想产生一个像这样的新列表:

List<string> newWords = new List<string>{ "apple", "computer", "user", "photo" };

How can I clean the first list from all the multiple words (no matter how they are written)? 如何清除所有多个单词中的第一个列表(无论它们是如何写的)?

many thanks in advance, Filippo 预先感谢,菲利波

Like this: 像这样:

List<string> newWords = words.Distinct(StringComparer.OrdinalIgnoreCase).ToList();

This way you don't change any words in the resulting list (eg making them lowercase). 这样,您就不会更改结果列表中的任何单词(例如,使其变为小写)。

You can also use: StringComparer.CurrentCultureIgnoreCase or StringComparer.InvariantCultureIgnoreCase , depending on your culture requirements. 您还可以使用: StringComparer.CurrentCultureIgnoreCaseStringComparer.InvariantCultureIgnoreCase ,具体取决于您的区域性要求。

List<string> words = new List<string> { "apple", "computer", "user", "AppLe", "USer", "photo", "USER" };
words = words.Select(x => x.ToLower()).Distinct().ToList();

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

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