none
Linq on generic object property RRS feed

  • Question

  • hello

    public T GetbyId(int id)
    {
                
          return connection.Table<T>().FirstOrDefault(x => x.Id == id);
    }

    i get error on the x.id!

    Error CS1061 'T' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

    so how to linq it?

    Tuesday, November 14, 2017 2:02 PM

All replies

  • That is correct. T is probably an object which doesn't have an Id property. If you want to require that T have this property then you need to put a constraint on T such that it implements an interface that has that property or derives from a type that does.

    public interface IIdentifable
    {
       int Id { get; }
    }
    
    public T GetbyId<T> ( int id ) where T: IIdentifable
    {
       return connection.Table<T>().FirstOrDefault(x => x.Id == id);
    }

    You didn't provide any context of what Table<T> returns but I assume it isn't EF or something like that. If it is EF then EF already has a Find method that can do exactly what you want without the need for the Id property. It already knows about PKs. For non-EF an expression might be the better route.

    public T GetbyId<T> ( Func<T, bool> finder )
    {
       return connection.Table<T>().FirstOrDefault(x => finder(x));
    }
    
    //Usage
    instance.GetbyId(x => x.Id == id);


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Fei HuModerator Wednesday, November 15, 2017 2:53 AM
    Tuesday, November 14, 2017 3:46 PM
    Moderator
  • Hello 2xo1,

    Do you have anything to update?  If you already have got the useful solution from there, you could close the thread by marking the useful reply as answer, This can be beneficial to other community members reading this thread. Thanks a lot.

    Sincerely,
    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Sunday, November 26, 2017 11:52 AM
    Moderator