Link to home
Start Free TrialLog in
Avatar of countrymeister
countrymeister

asked on

How can I dynamically create a filter on a generic list

I have a generic List, and I need to create a filter on this list

Not sure if this is possible, I need to replace the row.Field with some dynamically created string

 var list = from rows in listData.AsEnumerable().Where(row => row.Field = sCol )
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Will the sCol variable vary from element to element in the List?
I don't know of any way to do this off hand. It is possible in scripting language like JavaScript to do something like this, but not in C#. Therefore, I can see why you might think it's possible.

The best solution I can offer is a switch statement:

switch(myThingy)
{
   case: ThingyOne:
      list = from rows in listData.AsEnumerable().Where(row => row.Field = sCol);
       break;
   case: ThingyTwo:
       list = from rows in listData.AsEnumerable().Where(row => row.SomethingElse= sCol);
       break;
}

Open in new window


Now, that's kind of old-school, though. You might be able to implement something that uses Functional Programming. I'm still learning that, myself, though
I have a generic List
If you do, then there's no need to call the AsEnumerable method. A List implements IEnumerable, so the LINQ methods are readily available without the need for AsEnumerable.

Also, a generic list of what? I suppose it's not strings. What does your class look like? In other words, if you have List<T>, show us the definition of "T".
Avatar of countrymeister
countrymeister

ASKER

FernandoSoto

The sCol value is a string whose value will not change.

Kaufmed
List <T>, T has 10 properties some of which are strings, decimals and bool.

Dan7el

Thanks for the suggestion, but I would have to code for every property, trying to avoid doing that.
Hi countrymeister;

Then this should just change the property Field to the value of sCol in every instance of the list.

// Some dynamically created strain
string sCol = "Dynamically created string";
    
listData.ForEach(row => row.Field =  sCol);

// The value of Field has been changed in all instance

Open in new window

FernandoSoto

I want the row.Field to be one of the fields that the user selects and sCol is the value that needs to be filtered, so if the user selected Field1 then I want to filter Field1 with the value sCol.

If Field2 was selected I want to filter Field2 with the value sCol.

I have been thinking of converting the list to a datatable and then doing dr["somefield"] = sCol

Dan7el's solution was another way of doing this.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial