简体   繁体   English

使用 Linq 将两个列表与顺序进行比较

[英]Compare two list with order using Linq

If list 1 has the following properties: {A,B,C} and list 2 has the following properties {A,C,B}, comparing them should give the result "not matched".如果列表 1 具有以下属性: {A,B,C}并且列表 2 具有以下属性 {A,C,B},则比较它们应该给出“不匹配”的结果。

The item order also needs to be same.项目顺序也需要相同。

不是假装得到这个作为答案,但对于未来到达这里的人来说,应该有效:

enumerable1.SequenceEqual(enumerable2);

I dont think you can do this in Linq...我不认为你可以在 Linq 中做到这一点......

Try something like this尝试这样的事情

public bool CompareOrderedLists<T>(List<T> one, List<T> theOther)
{
    if(one.Length != theOther.Length) return false;

    for(var i = 0; i < one.Length; i++)
    {
        if(one[i] != theOther[i]) return false;
    }
    return true;
}

What you want ?你想要什么 ?

Compare two lists, with any order of elements.比较两个列表,元素的任何顺序。

Following is the Generic code:以下是通用代码:

internal class GenericListComparer<T>
{
    internal static bool Compare(List<T> firstCollection, List<T> secondCollection)
    {
        return firstCollection.TrueForAll(secondCollection.Contains) &&
               secondCollection.TrueForAll(firstCollection.Contains);
    }
}

Usage:用法:

List<int> aList = new List<int> { 1,2,3,4};

List<int> bList = new List<int> { 1,4,3,2};

bool result  = GenericListComparer<int>.Compare(aList,bList); // Matched

bList = new List<int> { 1,4,3,2,5};

result  = GenericListComparer<int>.Compare(aList,bList); // Un-Matched

Time Complexity - O(n)时间复杂度 - O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM