比较两个列表的数量-具有给定的公差

时间:2018-11-06 09:59:47

标签: c# list

我想比较两个列表,它们都可以为null,都可以包含0或更多条目。

如果数量匹配,应该对此进行一些处理。
如果不是,则应检查给定的公差是否涵盖了数量差异。

这就是我所做的。有没有更优雅的方法可以做到这一点?

int tolerableDifference = 5; //example.                
Result success = Result.Valid;

if (listA.Count == listB.Count)
{
  // do whatever is to be done when counts match. 
}
else
{
    // Lists have different length. No match.
    var absDifference = Math.Abs(listA.Count - listB.Count);

    if ((listA.Count - listB.Count) > 0)
    {
        if (absDifference < tolerableDifference)
        {
            Console.WriteLine($"Difference below Tolerance threshold. Difference: {absDifference}.");
        }
        else
        {
            //Outside tolerance, too less items in listB
            success = Result.Invalid | Result.TooFewItems;
        }
    }
    else if ((listA.Count - listB.Count) < 0)
    {
        if (absDifference < tolerableDifference)
        {
            Console.WriteLine($"Difference below Tolerance threshold. Difference: {absDifference}.");
        }
        else
        {
            //Outside tolerance, too many items in listB
            success = Result.Invalid | Result.TooManyItems;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我喜欢C#7中引入的新开关功能:

  switch (listA.Count - listB.Count)
  {
    case 0:
      // do whatever
      break;

    case int n when n > 0 && n < tolerableDifference:
      Console.WriteLine($"Difference below Tolerance threshold. Difference: {n}.");
      break;

    case int n when n >= tolerableDifference:
      success = Result.Invalid | Result.TooManyItems;
      break;

    case int n when n < 0 && n > -tolerableDifference:
      Console.WriteLine($"Difference below Tolerance threshold. Difference: {-n}.");
      break;

    case int n when n <= -tolerableDifference:
      success = Result.Invalid | Result.TooFewItems;
      break;

  }

答案 1 :(得分:1)

喜欢这个吗?

int tolerableDifference = 5; //example.                
Result success = Result.Valid;

var countA = listA == null?0:listA.Count;
var countB = listB == null?0:listB.Count;

if(coutA == countB)
{
  // do whatever is to be done when counts match. 
}
else
{
    var diff = countA - countB;
    var absDiff = Math.Abs(diff);
    if(absDiff < tolerableDifference)
    {
        Console.WriteLine($"Difference below Tolerance threshold. Difference: {absDiff}.");
    }
    else
    {
        success = Result.Invalid | (diff>0?Result.TooFewItems:Result.TooManyItems);
    }
}