I have a list of objects in which I want to remove duplicates but does not want to remove blank objects. I am using DistinctBy lambda expression. But it also removes duplicates. Can anyone help me in providing the condition that passes blank and checks only that object which has proper value in an object ?
how to remove duplicate values from a list but want to include all empty strings from that list
190 Views Asked by Ankur Gupta At
2
There are 2 best solutions below
5

Example:
var list is in this case a list consisting of all duplicates (minus the empty strings) then I just iterate through the duplicates and remove them from the listOfValues.
List<string> listOfValues = new List<string> {"test", "test2", "", "test2", "", ""};
var list = listOfValues.GroupBy(r => r).SelectMany(grp => grp.Skip(1)).Where(r => r != "");
foreach (var aVar in list)
{
listOfValues.Remove(aVar);
}
You could use a very simple extension method: