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?
CodePudding user response:
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));
CodePudding user response:
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");
}
}
CodePudding user response:
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 returnRejected
- if we don't have
Rejected
but at least oneSubmitted
then we returnSubmitted
- we return
Approved
if and only if all the items areApproved
This can be written as
var result = statuses.MaxBy(item => Array.IndexOf(
new [] { "Approved", "Submitted", "Rejected" }, item));