算法:计算两个大量数据的数组交集,差集,并集,(数据差异)
现有两个简单数组 List<string> 分别为 a
和 b
计算两个字符串数组 a
有 b
没有的字符串
立马就写出了Linq算法
List<string> a = new List<string>(); List<string> b = new List<string>(); var data = a.Where(w => !b.Any(t => t == w)).ToList();
GarsonZhang www.yesdotnet.com
数据量不大的时候没问题,如果数据量大的时候效率就很慢很慢,可以测试下 a 和 b 中各有12W条数据的情况,速度简直是惨不忍睹
提高效率的方法
使用Linq扩展
var dta = a.Except(b);
GarsonZhang www.yesdotnet.com
测试发现几乎是秒级别的效率了,固该方法效率很快,
另外还有几个扩展值得记住
string[] arrRate = new string[] { "a", "b", "c", "d" };//A string[] arrTemp = new string[] { "c", "d", "e" };//B string[] arrUpd = arrRate.Intersect(arrTemp).ToArray();//相同的数据 (结果:c,d) string[] arrAdd = arrRate.Except(arrTemp).ToArray();//A中有B中没有的 (结果:a,b) string[] arrNew = arrTemp.Except(arrRate).ToArray();//B中有A中没有的 (结果:e)
GarsonZhang www.yesdotnet.com
进阶学习之原理刨析
为什么Linq的扩展方法效率提升这么多呢?好在Linq是开源的,查看下源代码,源码太长,这里截取几个重要的片段
.net 源代码下载 Download (microsoft.com)
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Linq { public static partial class Enumerable { public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) { if (first == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } return ExceptIterator(first, second, null); } public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { if (first == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } return ExceptIterator(first, second, comparer); } private static IEnumerable<TSource> ExceptIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { Set<TSource> set = new Set<TSource>(comparer); set.UnionWith(second); foreach (TSource element in first) { if (set.Add(element)) { yield return element; } } } } }
GarsonZhang www.yesdotnet.com
完整的System.Linq代码参考:
corefx/src/System.Linq/src/System/Linq at master · dotnet/corefx · GitHub
corefx/Except.cs at master · dotnet/corefx · GitHub
我们第一次 where
嵌套 any
的写发,重复度为 MN
Linq扩展方法 Except
重复度为 M + N
大量数据的情况下效率显而易见
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post YES开发框架