Linq with a long where clause

Is there a better way to do this? I tried to loop into the partsToChange collection and create a where clause, but that AND them together instead of ORing. I also do not want to explicitly do equality for each element in the partsToChange list.

var partsToChange = new Dictionary<string, string> {
    {"0039", "Vendor A"},
    {"0051", "Vendor B"},
    {"0061", "Vendor C"},
    {"0080", "Vendor D"},
    {"0081", "Vendor D"},        
    {"0086", "Vendor D"},
    {"0089", "Vendor E"},
    {"0091", "Vendor F"},
    {"0163", "Vendor E"},
    {"0426", "Vendor B"},
    {"1197", "Vendor B"}
};

var items = new List<MaterialVendor>();
foreach (var x in partsToChange)
{
    var newItems = (
    from m in MaterialVendor 
    where 
        m.Material.PartNumber == x.Key 
        && m.Manufacturer.Name.Contains(x.Value)
    select m
    ).ToList();
    items.AddRange(newItems);
}

Additional Information: I work in LINQPad, and this is a LinqToSql query. Here MaterialVendor is a class and a DataContext table.

Edit: LinqToSql data.

This is apparently the best method I have found for both readability and complexity. It also has the added benefit of not explicitly specifying a collection type. This means that I can change what is returned with an anonymous type.

var predicate = PredicateBuilder.False<MaterialVendor>();

foreach (var x in partsToChange)
{
    var item = x;
    predicate = predicate.Or (m =>
        m.Material.PartNumber == item.Key 
        && m.Manufacturer.Name.Contains(item.Value));
}

var items = from m in MaterialVendor.Where(predicate)
    select m;
+3
3

PredicateBuilder

Linq to sql , AND/OR, , .

+2

[] , partToChange - Dictionary:

var items = MaterialVendor.Where(m =>
                m.Manufacturer.Name.Contains(partsToChange[m.Material.PartNumber])
            ).ToList();
+8

The size of the where clause does not matter. Querying in a loop is a part that reduces maintainability and performance.

List<MaterialVendor> items = 
(
  from z in MaterialVendor
  let partKey = z.Material.PartNumber
  where partsToChange.ContainsKey(partKey)
  let partValue = partsToChange[partKey]
  where z.Manufacturer.Name.Contains(partValue)
  select z
).ToList();

Now that we know that linq to sql is involved ... here the query is in mixed mode.

List<string> keys = partsToChange.Keys.ToList();

List<MaterialVendor> items =  
( 
  from z in MaterialVendor 
  let partKey = z.Material.PartNumber 
  where keys.Contains(partKey)
  select new {MatVendor = z, Name = z.Manufacturer.Name, Key = partKey}
).AsEnumerable()
.Where(x => x.Name.Contains(partsToChange[x.partKey]))
.Select(x => x.MatVendor)
.ToList(); 
0
source

Source: https://habr.com/ru/post/1746909/


All Articles