问题
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?
回答1:
You only have to write:
var filteredList = students.Where(student => classes.ContainsKey(student));
Here, student
is a string
, since students
is a List<string>
, so you only have to apply Where(). The result will be an IEnumerable<string>
.
You can apply ToList() if you want to exhaust the enumerable into another List<string>
:
var filteredList = students.Where(student => classes.ContainsKey(student)).ToList();
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:
var filteredList = students.Where(student => classes.ContainsKey(student))
.Select(student => classes[student]);
回答2:
try:
var filteredList = students.Where(k => classes.ContainsKey(k))
.Select(k => students[k]);
回答3:
var filteredList = students.Where(k => classes.ContainsKey(k))
.Select(k => students[k]);
来源:https://stackoverflow.com/questions/12146296/linq-casting-during-enumeration