zjh
3 天以前 da3b2cfb3a34a7b1f83dcd9fc762b1d2459547dc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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));
    }
}