Reputation: 183
I have a generic list and trying to get item based on value i.e.,
list.FirstOrDefault(u=>u.Key == key) // error 'T' does not contain definition for 'Key'
The generic type T
having different base classes.
Upvotes: 0
Views: 3212
Reputation: 14007
When using generic methods, you have to be sure your T has a property Key
. That can be achieved with generic constraints. That can be either a base class or an interface:
interface IKeyedObject {
string Key { get; };
}
class BaseWithKey : IKeyedObject {
public string Key { get; set; };
}
class DerivedA : BaseWithKey {
}
class DerivedB : BaseWithKey {
}
class OtherWithKey : IKeyedObject {
public string Key { get; set; };
}
//Solution with base class (will work with BaseWithKey, DerivedA, DerivedB)
T GetItemBaseClass<T>(List<T> list, string key)
where T : BaseWithKey {
return list.FirstOrDefault(u=>u.Key == key);
}
//Solution with interface (will work with all classes)
T GetItemInterface<T>(List<T> list, string key)
where T : IKeyedObject {
return list.FirstOrDefault(u=>u.Key == key);
}
Upvotes: 2
Reputation: 41
You are trying to use Key while T is not specified and thus we do not know if T class contains any field/property Key. On thing you can do is to use abstract class/interface or to try to cast u into the class that contains "Key" (assuming you are expecting some classes specificly). Some more details about your list and its items are needed for a more precise answer. Hope it can help !
Upvotes: 1
Reputation: 190915
Depending on where your T
is getting filled into List<T>
, you could specify generic constraints on it to have an interface (or base class).
Interface:
interface IHasKey { string Key { get; } } // or some other type for `Key`
Generic constraint:
where T : IHasKey
Upvotes: 3