1

I am working on an application where I have a list of statuses like Submitted, Approved, and Rejected. In my scenario when all the statutes are Approved then I have to return Approved but if there is a single record that is Rejected then will return Rejected. If there is a record with the status Submitted and the other two are Approved then return Submitted. I have implemented a simple check base logic but I need to make it better with best practices and more generic.

List<string> statuses = new List<string>() { "Approved", "Approved", "Approved" };
var res = statuses.Where(x => x == "Approved").ToList();
    
if (res.Count() == statuses.Count())
{
    Console.WriteLine("Approved");
}

if (res.Where(x => x == "Rejected").Count() > 0)
{
    Console.WriteLine("Rejected");
}
else
{
    Console.WriteLine("Submitted");
}

How can I achieve this and improve my logic?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Muhammad Kamran
  • 105
  • 1
  • 11

3 Answers3

3
List<string> statuses = new List<string>() { "Approved", "Approved", "Submitted" };

if (statuses.All(x => x == "Approved"))
{
    System.Console.WriteLine("Approved");
}
else
{
    if (statuses.Any(x => x == "Rejected"))
    {
        System.Console.WriteLine("Rejected");
    }
    else
    {
        System.Console.WriteLine("Submitted");
    }
}
mrsridhar
  • 51
  • 5
2

You could simplify the logic like this:

Have a function to work out the status:

private static string GetStatus(List<string> statuses) 
{
        if (statuses.Any(x => x == "Rejected")) return "Rejected";
        if (statuses.All(x => x == "Approved")) return "Approved";
        return "Submitted";
}

Call it like this:

Console.WriteLine(GetStatus(statuses));
Donal
  • 31,121
  • 10
  • 63
  • 72
  • How about If I define an extra list which contain all the three statuses is there any way to compare for status check. – Muhammad Kamran Jun 29 '22 at 10:59
  • @MuhammadKamran sure you can do something like this, check if any in List 1 match any in List 2.: List1.Any(x => List2.Any(y => y == x)); – Donal Jun 29 '22 at 11:02
1

So we have a clear order

Approved < Submitted < Rejected

and we want to find out a maximum:

  • if we have at least one Rejected we return Rejected
  • if we don't have Rejected but at least one Submitted then we return Submitted
  • we return Approved if and only if all the items are Approved

This can be written as

var result = statuses.MaxBy(item => Array.IndexOf(
  new [] { "Approved", "Submitted", "Rejected" }, item));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215