Search code examples
c#linqmorelinq

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


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 ?


Solution

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