LINQ casting during enumeration

自古美人都是妖i 提交于 2019-12-14 02:34:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!