I have a List<string>
List<string> students;
students.Add("Rob");
students.Add("Schulz");
and a Dictionary<string,string>
Dictionary<string, string> classes= new Dictionary<string, string>();
classes.Add("Rob", "Chemistry");
classes.Add("Bob", "Math");
classes.Add("Holly", "Physics");
classes.Add("Schulz", "Botany");
My objective now is to get a List with the values – Chemistry and Botany – for which I am using this
var filteredList = students.Where(k => classes.ContainsKey(k))
.Select(k => new { tag = students[k] });
While trying to enumerate the values – I am able to obtain – tag=Chemistry & tag=Botany…while I want just Chemistry and Botany.
What is the appropriate casting to be applied? Is there a better way to get to these values?
You only have to write:
Here,
studentis astring, sincestudentsis aList<string>, so you only have to apply Where(). The result will be anIEnumerable<string>.You can apply ToList() if you want to exhaust the enumerable into another
List<string>:If you want a list of classes (it’s not clear from the code in your question), then you have to apply Select() to project classes from students: