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")); }
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With