Сравните количество двух списков - с заданным допуском - PullRequest
0 голосов
/ 06 ноября 2018

Я хочу сравнить два списка, оба из которых могут быть нулевыми, оба могут содержать 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 голосов
/ 06 ноября 2018

Как это?

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);
    }
}
0 голосов
/ 06 ноября 2018

Мне нравятся новые улучшения коммутатора, представленные в 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;

  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...