bicko
bicko

Reputation: 13

A better way than repeated exception filter?

It is possible to write code like this, but without repeating user exception filter.

 foreach (var val in users)
 {
    if (val.Any(x => x.UserException.Contains("QPZ") || x.UserException.Contains("QPR")))
    {
        listUsers.Add(
        val?.First( s => s.UserException.Contains("QPZ") || 
                         s.UserException.Contains("QPR")));
    }
    else
    {
        listUsers.AddRange(val);
    }
 }

Upvotes: 0

Views: 74

Answers (3)

bicko
bicko

Reputation: 13

Thanks to Ivan and JanR I found the answer to my question, thank you so much!

var exceptionList = new List<string> {"QPZ","QPR"};

foreach (var val in users)
{

 var match = val.FirstOrDefault(x => exceptionList.Contains(x.UserException));

   if (match != null)
   {
      usersList.Add(match);
   }
   else
   {
      usersList.AddRange(val);
   }
}

Upvotes: 0

Ivan Stoev
Ivan Stoev

Reputation: 205759

You can avoid duplicate filter (and also improve the performance) by replacing the Any(filter) + First(filter) with FirstOrDefault(filter) + null check:

foreach (var val in users)
{
    var match = val.FirstOrDefault(x => 
        x.UserException.Contains("QPZ") || x.UserException.Contains("QPR"));
    if (match != null)
    {
        listUsers.Add(match);
    }
    else
    {
        listUsers.AddRange(val);
    }
 }

Upvotes: 3

JanR
JanR

Reputation: 6132

You could use a list of exceptions and check against that:

var exceptionList = new List<string> {
  "QPZ",
  "QPR"
};

foreach (var val in users)
 {
    if (val.Any(x => exceptionList.Contains(x.UserException))
    {
        listUsers.Add(
           val?.First(s => exceptionList.Contains(x.UserException))
        );
    }
    else
    {
        listUsers.AddRange(val);
    }
 }

Upvotes: 0

Related Questions