Find item from generic list

蓝咒 提交于 2021-01-27 07:43:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!