如何过滤通用方法中的集合 [英] How to filter a collection inside a generic method
问题描述
我有一个两个类,它有以下属性:
pre $ $ $ $ $ $ {
public int CustID {get;组; }
public bool isProcessed {get;组; }
}
类B
{
public int EmpId {get;组; }
public bool isProcessed {get;组; }
}
我创建了一个接受所有这些类的泛型方法。'isProcessed'属性
public void ProceesData< T>(IList< T> param1,string date1)
{
}
我需要以下的东西
- 内部ProcessData方法我想筛选具有
isProcessed标志的项目是True。 另外 - 我想迭代这个集合,并且需要为IsProcessed属性设置值。
注意:我更喜欢使用反射的解决方案,因为属性名称是恒定的(即IsProcessed)
任何人都可以帮助解决这个问题。
最简单的方法是确保两个类实现一个通用接口并约束泛型方法。例如:
public interface IProcessable
{
bool isProcessed {get;组; }
}
public class A:IProcessable
{
public int CustID {get;组; }
public bool isProcessed {get;组; }
}
public class B:IProcessable
{
public int EmpId {get;组; }
public bool isProcessed {get;组; }
}
现在您的方法如下所示:
public void ProceesData< T>(IList< T> param1,string date1)
其中T:IProcessable //<
{
foreach(param1中的var元素)
{
element.isProcessed = true;
}
}
如果您不能使用接口或属性名称会有所不同,是将 Action< T>
作为参数传递给您的方法。例如:
public void ProceesData< T>(IList< T> param1,string date1,Action< T> func) b $ b {
foreach(param1中的var元素)
{
func(element);
并且像这样调用它:
ProceesData< A>(list,,x => x.isProcessed = true);
I have a two class which is having following properties
Class A
{
public int CustID { get; set; }
public bool isProcessed { get; set; }
}
Class B
{
public int EmpId{ get; set; }
public bool isProcessed { get; set; }
}
I created one generic method which accepts all these classes.'isProcessed' property is common in both these classes.
public void ProceesData<T>(IList<T> param1, string date1)
{
}
I need following things
- Inside ProcessData method i want to filter items which is having isProcessed flag is "True".
- Also i want to iterate this collection and need to set values for IsProcessed property.
Note: I am preferring solution using reflection,since property name is constant (ie "IsProcessed")
Can anyone help on this.
The easiest way is to ensure that both classes implement a common interface and constrain your generic method. For example:
public interface IProcessable
{
bool isProcessed { get; set; }
}
public class A : IProcessable
{
public int CustID { get; set; }
public bool isProcessed { get; set; }
}
public class B : IProcessable
{
public int EmpId { get; set; }
public bool isProcessed { get; set; }
}
Now your method would look like this:
public void ProceesData<T>(IList<T> param1, string date1)
where T : IProcessable // <-- generic constraint added
{
foreach (var element in param1)
{
element.isProcessed = true;
}
}
Another option which is more useful if you cannot use an interface or the property names vary, is to pass in an Action<T>
as a parameter to your method. For example:
public void ProceesData<T>(IList<T> param1, string date1, Action<T> func)
{
foreach (var element in param1)
{
func(element);
}
}
And call it like this:
ProceesData<A>(list, "", x => x.isProcessed = true);
这篇关于如何过滤通用方法中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!