问题
I have a problem in fetching the record from a generic list. I have created a common function from where i want to get the records from any type of class. Below is sample code:-
public void Test<T>(List<T> rEntity) where T : class
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
Please suggest. Thanks in advance.
回答1:
With method like that a usual question for compiler is 'what is T' ?
If it's just a class it could be anything even a StringBuilder
as Jon has mentioned and there is no guarantee that it has a property 'Id'. So it won't even compile the way it is right now.
To make it work we have two options :
A) Change the method and let compiler know what type to expect
B) Use reflection and use run-time operations (better avoid this when possible but may come handy when working with 3rd party libraries).
A - Interface solution :
public interface IMyInterface
{
int Id {get; set;}
}
public void Test<T>(List<T> rEntity) where T : IMyInterface
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
B - Reflection solution:
public void Test<T>(List<T> rEntity)
{
var idProp = typeof(T).GetProperty("Id");
if(idProp != null)
{
object id = 1;
var result = rEntity.Where(x => idProp.GetValue(x).Equals(id));
}
}
回答2:
You most define a basic class that have id property and your T most be inherit from that basic class.
public class BaseClass{
public object ID;
}
and you can change your function like this:
public void Test<T>(List<T> rEntity) where T : BaseClass
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
来源:https://stackoverflow.com/questions/43366996/find-item-from-generic-list