using System.Collections.Generic;
using System.Runtime.InteropServices;
public static class Program
public static void Main()
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass() { BillId = "123" });
list.Add(new MyClass() { BillId = "777" });
list.Add(new MyClass() { BillId = "999" });
list.Add(new MyClass() { BillId = "123" });
List<MyClass> unique = list.UniqueBy(x => x.BillId).ToList();
Console.WriteLine(string.Join(", ", unique.Select(x => x.BillId)));
public object classObj {get;set;}
public string BillId {get;set;}
public static IEnumerable<TSource> UniqueBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer = default)
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(keySelector);
Dictionary<TKey, (TSource Item, bool Unique)> dictionary = new(comparer);
if (source.TryGetNonEnumeratedCount(out int count))
dictionary.EnsureCapacity(count);
foreach (TSource item in source)
CollectionsMarshal.GetValueRefOrAddDefault(dictionary, keySelector(item),
out bool exists) = exists ? default : (item, true);
foreach ((TSource item, bool unique) in dictionary.Values)