0

I want to write where statement dynamically.

ex.

public class MyClass {
public int id {get; set;}
public string name {get; set;}
}

List<MyClass> myClasses = GetMyClass();
List<int> numbers = new List<int>{1,5,6};

for(int i = 0; i < numbers.Count(); i++)
{
    myClasses += .Where(class => class.id = numbers[i])
}

var result = myClasses;

I want the same result as the result of

myClasses.Where(class => class.id = 1).Where(class => class.id = 5).Where(class => class.id = 6)

But my code gives a compile error now...

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • if you want to select all classes with id in your numbers list. why not use `myClasses.Where(class => numbers.Contains(class.id)))` – Searching Oct 23 '19 at 06:16

4 Answers4

1

I believe you just simply need the Contains method, something like this

myClasses.Where(c => numbers.Contains(c.id))
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

To chain multiple where predicates like this you need:

myClasses = myClasses.Where(class => class.id == numbers[i])

But for this to compile, change myClasses declaration to IEnumerable<MyClass> myClasses = ...

ghord
  • 13,260
  • 6
  • 44
  • 69
1

If you want all "myClasses" with id contained in another list, you just have to execute :

public void Filter()
{
    ...
    var result = myClasses.Where(c => numbers.Contains(c.id));
    ...
}

Assuming myClasses and numbers are declared before, and you do something with "result". To effectively run the Where condition, do not forget the .ToList(), as usual.

PS: your "desired" behavior in the first post is complete nonsense, as it would mean "Find all MyClass instances having AT THE SAME TIME id=1, 5 and 6.

Also, you seem to have lacks and misunderstandings on fundamentals of lambda expressions writing, beyond the logic itself it seems you should try to improve on this topic too.

fkirchw
  • 7
  • 1
  • 2
AFract
  • 8,868
  • 6
  • 48
  • 70
0
public IOrderedQueryable<Detail> GetProductList(string GroupName, string TypeName, Dictionary<string,List<string>> filterDictionary)
{
    var q = from c in db.Detail
            where c.GroupName == GroupName && c.TypeName == TypeName
            // insert dynamic filter here
            orderby c.TypeName
            select c;
    return q;
}