[英]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.问题在这里: item.ITEMGROUP根据运行此功能的内容而有所不同。
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.我使用字符串作为“键”的示例,它可以是 ITEMGROUP 或其他东西。
var mylist = list.Where(item => item[key].Contains(groupidListItem)).ToList();
I would just pass this part item => item[key].Contains(groupidListItem)
with a delegate:我只想通过委托传递这部分item => item[key].Contains(groupidListItem)
:
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);
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
.这样您就可以重用该函数并根据T
的类型传递您需要的过滤器。
Also you don't need a foreach for this:此外,您不需要 foreach :
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.