c#将两个数组与条件进行比较

时间:2011-07-25 19:33:21

标签: .net c#-4.0

如果我有两个阵列

   First: A, B, C
   Second: ?, B, C

我想只比较Second中的项目和First中不包含问号“?”的项目。

所以对于这种情况:

   First: A, B, C
   Second: ?, B, C

我想比较第1项和第2项,因为第二个数组中的第0项包含?。

对于那个:

   First: A, B, C
   Second: 2, ?, C

我想只比较第0和第2项,因为第二个数组中的第1项包含?

任何想法如何更好,最少的代码来做到这一点?如果需要创建任何列表或任何其他集合,那就没问题了。

4 个答案:

答案 0 :(得分:3)

KISS

for(int i = 0; i < listB.length; i++)
   if(listB[i] != "?")
       compare(listA[i], listB[i]);

答案 1 :(得分:2)

在舒适的扶手椅上使用LINQ:

// Input data:
var first = new[] { "A", "B", "?" };
var second = new[] { "?", "B", "C" };

// This actually filters out pairs where either first or second
// is equal to "?". If you only want to filter out pairs where the
// second is "?", adjust accordingly.
var toCompare = first.Zip(second, Tuple.Create)
                     .Where(t => t.Item1 != "?" && t.Item2 != "?");

// And now you have a collection of Tuple<string, string>, which
// can be processed in a multitude of ways:
Console.Out.WriteLine(string.Format(
    "Compared {0} items, and found {1} of them equal.",
    toCompare.Count(),
    toCompare.All(t => t.Item1 == t.Item2) ? "all" : "not all"));            

<强>更新

如果比较谓词(比较一对项并返回布尔值的方法)将比上面的更复杂,那么将它定义为lambda(如果它不会被重用和它足够短)或作为一种正确的方法。

例如,要实现以下评论中提到的内容:

Func<Tuple<string, string>, bool> predicate = t =>
    t.Item2 == "?" ||
    t.Item2 == "_" && t.Item1 != string.Empty ||
    t.Item2 == t.Item1;

// And now you have a collection of Tuple<string, string>, which
// can be processed in a multitude of ways:
Console.Out.WriteLine(string.Format(
    "Compared {0} items, and found {1} of them equal.",
    toCompare.Count(),
    toCompare.All(predicate) ? "all" : "not all"));            

答案 2 :(得分:1)

您需要的不是以下内容吗?

for (int ii = 0; ii < second.Length; ii++)
{
    if (second[ii] == "?")
        continue;

    // Else do your compare.
}

答案 3 :(得分:1)

[TestMethod]
public void TestArrayWithConditions()
{
    var First = new [] {"A", "B", "C"};
    var Second = new[] { "?", "B", "C" };
    var Third = new[] { "2", "?", "C" };

    var result12 = CompareWithConditions(First, Second);
    var result13 = CompareWithConditions(First, Third);

    Assert.AreEqual(null, result12[0]);
    Assert.AreEqual(true, result12[1]);
    Assert.AreEqual(true, result12[2]);

    Assert.AreEqual(false, result13[0]);
    Assert.AreEqual(null, result13[1]);
    Assert.AreEqual(true, result13[2]);
}

private static List<bool?> CompareWithConditions(string[] first, string[] second)
{
    var result = new List<bool?>();

    var length = Math.Min(first.Length, second.Length);

    for (int i = 0; i < length; i++)
    {
        if (second[i] == "?")
        {
            result.Add(null);
        }
        else
        {
            result.Add(second[i] == first[i]);
        }
    }

    return result;
}