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).
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
Tas input, and return astringorobjectas the output, you can mimic that functionality:From the calling side it might look something like this (to use your first code snippet as an example: