假设我有这两个数组:
var array1 = new[] {"A", "B", "C"};
var array2 = new[] {"A", "C", "D"};
我想要获取两者之间的差异。我知道我可以用几行代码来实现这个功能,但我想确保自己没有漏掉任何内置的语言特性或LINQ扩展方法。
理想情况下,我希望得到以下三个结果:
- 不在array1中,但在array2中的项(“D”)
- 不在array2中,但在array1中的项(“B”)
- 在两者中都存在的项
来自MSDN 101 LINQ示例....
public void Linq52() {
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers) {
Console.WriteLine(n);
}
}
我曾经需要处理非常大的数据集,类似于这样的事情。如果你只处理几千个数据,使用Linq会更清晰明了。但是,如果你知道你的数组已经预先排序好了,那么运行像这样的合并操作可以显著提高速度,因为它只通过一次数据并且不需要像Linq版本那样分配太多内存。
int iA = 0;
int iB = 0;
List<int> inA = new List<int>();
List<int> inB = new List<int>();
List<int> inBoth = new List<int>();
while (iA < numbersA.Length && iB < numbersB.Length)
{
if (numbersA[iA] < numbersB[iB])
{
inA.Add(numbersA[iA++]);
}
else if (numbersA[iA] == numbersB[iB])
{
inBoth.Add(numbersA[iA++]);
++iB;
}
else
{
inB.Add(numbersB[iB++]);
}
}
while (iA < numbersA.Length)
{
inA.Add(numbersA[iA++]);
}
while (iB < numbersB.Length)
{
inB.Add(numbersB[iB++]);
}
如果您要处理数十万个值,才真正需要这样做。
public class Key : IEquatable<Key>
{
public int Index { get; private set; }
public string Name { get; private set; }
public Key(string keyName, int sdIndex)
{
this.Name = keyName;
this.Index = sdIndex;
}
// IEquatable implementation
public bool Equals(Key other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return Index.Equals(other.Index) && Name.Equals(other.Name);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
//Get hash code for the name field if it is not null.
int hashKeyName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the index field.
int hashKeyIndex = Index.GetHashCode();
//Calculate the hash code for the Key.
return hashKeyName ^ hashKeyIndex;
}
}
int[] arr1 = new int[] { 45, 26, 99, 55, 36 };
int[] arr2 = new int[] { 45, 26, 99, 20, 36 };
var res = arr1.Union(arr2).Except(arr1.Intersect(arr2));
for
循环,速度要快得多...先试试它,看看它是否真的像你想象的那么慢...我怀疑它不会。 - Drunken Code Monkey