Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove empty strings from list, then remove duplicate values from a list

Tags:

c#

linq

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:

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"));        } 
like image 400
Developer Avatar asked Aug 08 '12 14:08

Developer


People also ask

How do I remove blank strings from a list?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.

How do I remove an empty value from a list?

The easiest way is list comprehension to remove empty elements from a list in Python. And another way is to use the filter() method. The empty string "" contains no characters and empty elements could be None or [ ], etc.

How do you remove null elements from a list in Python?

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.


1 Answers

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

like image 51
Amiram Korach Avatar answered Sep 30 '22 02:09

Amiram Korach