I am trying to filter a list of Chord objects (class) in C# using linq.
I have the following function in my class
public List<Chord> FilterDictionary_byKey<Chord>(string theKey)
{
var filteredList = from item in _chords
where item.KeyName == theKey
select item;
return (List<Chord>)filteredList;
}
in the above Chord is an object type, _chords is a class variable of List type.
then from my calling code I tried the following:
List<Chord> theChords = globalVariables.chordDictionary.FilterDictionary_byKey("A");
obviously trying to return a filtered list of Chord objects from the class
however, when i compile the compiler returns
Error 1 The type arguments for method ‘ChordDictionary.chordDictionary.FilterDictionary_byKey(string)’ cannot be inferred from the usage. Try specifying the type arguments explicitly. C:\Users\Daniel\Development\Projects\Tab Explorer\Tab Explorer\Forms\ScaleAndChordViewer.cs 75 37 Tab Explorer
The inferred type of a
from…selectLINQ query is actually anIEnumerable<T>, which is not a populated list or collection, but a sequence that will be enumerated on demand. Casting it toList<T>does not cause this enumeration; instead, you should callToList()orToArray().To address the error you’re getting: Your method declaration should not have a generic type parameter, since neither its return type nor any of its parameters are generic. Just remove the
<Chord>following the method name.