Home > Software design >  How to return a list of entities with a given string range?
How to return a list of entities with a given string range?

Time:11-20

I'm trying to get a list of Vendors' names where the name starts with a character between A and E. Is there a way to do that perhaps using LINQ?

My current solution is just a very long if statement

var vendors = _context.Vendors.ToList();
var sortedVendors = new List<Vendor>();

foreach (Vendor vendor in vendors)
{
    if (vendor.Name.StartsWith('A') ||
        vendor.Name.StartsWith('B') ||
        vendor.Name.StartsWith('C') ||
        vendor.Name.StartsWith('D') ||
        vendor.Name.StartsWith('E'))
    {
        sortedVendors.Add(vendor);
    }
}

This works, but is hideous and I would love to know if there was a more elegant solution

CodePudding user response:

This is how I would do it

var charsToCheck = new char[] { 'A', 'B', 'C', 'D', 'E' };
var sortedVendors = vendors.Where(vendor => charsToCheck.Contains(vendor[0])).ToList();

CodePudding user response:

To make it clear and readable I think I would do this:

string startsWiths = "ABCDEF";

IEnumerable<Vendor> query =
    from v in vendors
    where startsWiths.Any(c => v.Name.StartsWith(c))
    select v;
    
List<Vendor> sortedVendors = query.ToList();
  • Related