roady
roady

Reputation: 597

C# Linq dynamic item property

Trying to make a reusable function to skip having the same code all over. The issue is that the key on where I do the match has a different name. Else it's all the same.

This is what I have so far. The issue is here: item.ITEMGROUP that is different depending on what is running this function.

public List<T> FilterGroupIds<T>(List<T> list, string key, string groupids)
{
    if (!string.IsNullOrEmpty(groupids))
    {
        string[] groupidList = groupids.Split(new char[] { ',' });
        List<T> grouped = new List<T>();
        foreach (string groupidListItem in groupidList)
        {
            var mylist = list
              .Where(item => **item.ITEMGROUP**.Contains(groupidListItem))
              .ToList();

            grouped.AddRange(mylist);
        }
        list = grouped;
    }
    return list;
}

Is there a way to use some kind of dynamic check? Example where I use a string to use as "key" that could be ITEMGROUP or something else.

var mylist = list.Where(item => item[key].Contains(groupidListItem)).ToList();

Upvotes: 2

Views: 104

Answers (1)

Alexander Derck
Alexander Derck

Reputation: 14488

I would just pass this part item => item[key].Contains(groupidListItem) with a delegate:

public List<T> FilterGroupIds<T>(List<T> list, string key, string groupids, 
                                 Func<T,bool> condition)
{
   ...
   var mylist = list.Where(condition).ToList();
}

with Func<T,bool> condition = item => **item.ITEMGROUP**.Contains(groupidListItem);. This way you can reuse the function and pass the filter you need based on the type of T.

Also you don't need a foreach for this:

return list.Where(item => groupIdList.Any(g => item.ITEMGROUP.Contains(g))
           .ToList();

is the same as

foreach (string groupidListItem in groupidList)
{
    var mylist = list
       .Where(item => **item.ITEMGROUP**.Contains(groupidListItem))
       .ToList();

    grouped.AddRange(mylist);
}
list = grouped;
return list;

Upvotes: 2

Related Questions