枚举期间的LINQ铸造 [英] LINQ casting during enumeration

查看:173
本文介绍了枚举期间的LINQ铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< string>

List<string> students;
students.Add("Rob");
students.Add("Schulz");

字典< 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"); 

我现在的目标是获取一个带有值的列表 - code>和植物学 - 我正在使用此

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] });

尝试枚举值时 - 我可以获取 - tag =化学& tag = Botany ...而我只想要化学 Botany

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?

推荐答案

你只需要写:

var filteredList = students.Where(student => classes.ContainsKey(student));

这里,学生 string ,因为学生 List< string> 必须应用 Where()。结果将是 IEnumerable< string>

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>.

您可以应用 ToList()如果你想将枚举排除到另一个 List< 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]);

这篇关于枚举期间的LINQ铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆