简体   繁体   中英

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();

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM