Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select property by string name using LINQ

Tags:

c#

.net

list

linq

I have a pretty simple piece of code:

var list = new List<MyType>();
list = MyItems.Where(x => x.Name.ToLower().Contains(e.Text.ToLower())).ToList();
for (int i = itemOffset; i < endOffset; i++)
{
    combo.Items.Add(new ComboItem(list[i].Name, list[i].Id.ToString()));
}

What I want to do is to make this a generic function that accepts list of any type and accepts two strings as properties. (In this case two properties that we are looking at are Name and Id.

private void MakeCombo<T>(Combo combo, IEnumerable<T> lst, string Field1, string Field2)
{
    var list = list = lst.Where(x => x.Field1.ToLower().Contains(searchText.ToLower())).ToList(); //How make this to work???

    for (int i = itemOffset; i < endOffset; i++)
    {
        combo.Items.Add(new ComboItem(list[i].Field1, list[i].Field2.ToString())); //How make this to work???
    }
}

Now, I do not understand how can I access properties of generic list by string names (Field1 and Field2).

like image 800
user194076 Avatar asked Apr 20 '26 11:04

user194076


1 Answers

One way of solving this problem, if you don't have the ability of creating an interface and ensuring all of the items in the sequence implement that interface (as shown in this other answer), is to use delegates. By passing in two functions, each of which take a T as input, and return a string or object as the output, you can mimic that functionality:

private void MakeCombo<T>(Combo combo, IEnumerable<T> sequence
    , Func<T, string> field1Selector, Func<T, object> field2Selector)
{
    var foundItems = sequence.Where(item => field1Selector(item).ToLower()
        .Contains(searchText.ToLower()));

    foreach(var item in foundItems)
    {
        combo.Items.Add(new ComboItem(field1Selector(item), field2Selector(item).ToString()));
    }
}

From the calling side it might look something like this (to use your first code snippet as an example:

MakeCombo(combo, list, item => item.Name, item => item.Id);
like image 82
Servy Avatar answered Apr 23 '26 00:04

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!