using System.Collections.Concurrent;
|
|
namespace MES.Service.util;
|
|
public static class LinqThreadSafeExtensions
|
{
|
// 线程安全版本(基于ConcurrentDictionary)
|
public static Func<T, bool> DistinctByKey<T, TKey>(
|
Func<T, TKey> keySelector)
|
{
|
var seen = new ConcurrentDictionary<TKey, bool>();
|
return item => seen.TryAdd(keySelector(item), true);
|
}
|
|
// 扩展方法版本(推荐)
|
public static IEnumerable<T> DistinctByConcurrent<T, TKey>(
|
this IEnumerable<T> source,
|
Func<T, TKey> keySelector)
|
{
|
var seen = new ConcurrentDictionary<TKey, bool>();
|
return source.Where(item => seen.TryAdd(keySelector(item), true));
|
}
|
}
|