CSharp - 如何从 List 中删除空字符串,然后从 List 中移除重复值

如何删除空字符串和重复的值,请参阅以下代码:


List<string> dtList = dtReportsList.AsEnumerable().Select(dr => dr.Field<string>("column1")).ToList();


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"));


 }

时间:


dtList = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()

如果不能使用IsNullOrEmpty (允许空白)或s != null


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();

返回相同的元素;

为了通用性,这里有一个替代方案。


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();

...