简体   繁体   中英

Find item from generic list

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.

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

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

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