C# 如何从列表中删除空字符串,然后从列表中删除重复值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11867070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove empty strings from list, then remove duplicate values from a list
提问by Developer
Lets say I have a list of some column values coming from a table, how do I remove empty strings and duplicate values. Please see the following code:
假设我有一个来自表的一些列值的列表,如何删除空字符串和重复值。请看以下代码:
List<string> dtList = dtReportsList.AsEnumerable().Select(dr => dr.Field<string>("column1")).ToList();
This is what I have coded just now but but Amiram's code is way more elegant, so I will choose that answer here is how I did it:
这是我刚刚编写的代码,但 Amiram 的代码更优雅,所以我会选择这里的答案是我是如何做到的:
DataTable dtReportsList = someclass.GetReportsList();
if (dtReportsList.Rows.Count > 0)
{
List<string> dtList = dtReportsList.AsEnumerable().Select(dr => dr.Field<string>("column1")).ToList();
dtList.RemoveAll(x=>x == "");
dtList = dtList.Distinct().ToList();
rcboModule.DataSource = dtList;
rcboModule.DataBind();
rcboModule.Items.Insert(0, new RadComboBoxItem("All", "All"));
}
采纳答案by Amiram Korach
dtList = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()
I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty(allow whitespace), or s != null
我假设空字符串和空格就像 null。如果不是,您可以使用IsNullOrEmpty(允许空格),或s != null
回答by KeithS
Amiram's answer is correct, but Distinct() as implemented is an N2operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.
Amiram 的回答是正确的,但 Distinct() 实现的是 N 2操作;对于列表中的每个项目,算法将其与所有已处理的元素进行比较,如果唯一则返回它,否则将其忽略。我们可以做得更好。
A sortedlist can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:
甲排序列表可以在线性时间内重复数据删除; 如果当前元素等于前一个元素,则忽略它,否则返回它。排序是 NlogN,所以即使必须对集合进行排序,我们也会得到一些好处:
public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
var toDedupe = input.OrderBy(x=>x);
T prev;
foreach(var element in toDedupe)
{
if(element == prev) continue;
yield return element;
prev = element;
}
}
//Usage
dtList = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();
This returns the same elements; they're just sorted.
这将返回相同的元素;他们只是排序。
回答by IneedHelp
Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.
Amiram Korach 解决方案确实很整洁。为了多功能性,这里有一个替代方案。
var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

