【问题标题】:LINQ Equivalent queryLINQ 等效查询
【发布时间】:2012-08-27 21:36:18
【问题描述】:

我有一个

 List<string>     

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

还有一个

Dictionary<string,string> 

Dictionary<string, string> courses = new Dictionary<string, string>(); 
courses .Add("Rob", "Chemistry");   
courses .Add("Bob", "Math");  
courses .Add("Holly", "Physics"); 
courses .Add("Schulz", "Botany");

我现在的目标是获得一个包含值的列表 - {Chemistry,Botany}

换句话说,我正在尝试获得 LINQ 的等价物

select value from [courses]
where [courses].key in 
(
select [courses].key from courses,students where [students].id LIKE '%courses.key%'
)

应该如何构建 LINQ 查询?

【问题讨论】:

标签: c# linq list dictionary linq-to-objects


【解决方案1】:

这是正确答案:

var values = from c in courses
             where students.Any(s => s.IndexOf(c.Key, StringComparison.OrdinalIgnoreCase) >= 0)
             select c.Value;

在我的机器上测试过。 希望这能有所帮助。

【讨论】:

  • 最好使用s.IndexOf(c.Key, StringComparison.OrdinalIgnoreCase) &gt;= 0 - 使用 ToLower() 不适合进行不区分大小写的比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2012-08-23
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多