how to remove duplicate values from a list but want to include all empty strings from that list

190 Views Asked by At

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 ?

2

There are 2 best solutions below

1
On BEST ANSWER

You could use a very simple extension method:

    public static void DistinctKeepingEmptyStrings(this List<string> list) {
        var support = new List<string>(list);
        HashSet<string> knownValues = new HashSet<string>();
        foreach (var aString in list) {
            if (aString == "" || knownValues.Add(aString)) {
                support.Add(aString);
            }
        }
        list.Clear();
        list.AddRange(support);
    }
5
On

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