【问题标题】:Using Foreach on iQueryable List find value if in 2nd List如果在第二个列表中,则在 iQueryable 列表上使用 Foreach 查找值
【发布时间】:2014-07-13 01:00:48
【问题描述】:

我有一个使用查询创建的 iQueryable 集合,如下所示 -

var Results = DataClass.Links.OrderBy(mySel => mySel.Description)
                             .Where(mySel =>                                     mySel.Report_Id.Equals(NumID)                                          
                             new Sections
                             {
                                SectID = mySel.Report_Section.SectID,
                                SectionDesn = mySel.Report_Section.ReportSectionDescription,
                                ReportPageTitle = mySel.tbl_Report.ReportPageTitle,                                                
                                MyUrl = mySel.Link_Url
                             }).Distinct();

我还有一个名为 LookForMe 的 List<string> 类型列表,定义为

var LookForMe = new List<string> { "increase", "abc", "tuesday", "another" };

我现在正在尝试遍历我的结果集合中的每个项目,如果 item.URL 包含在我的 LookForMe 列表中找到的值之一,如果是,那么做一些事情。

foreach (var item in Results)
{
   if (item.URL *contains any of the values in my LookFormE list*)
   {
      // then do something
   }
}

我不确定如何编写 if 语句来查找当前迭代值是否包含 LookForMe 列表中的任何值。有什么想法可以让我走上正轨吗?感谢您的宝贵时间。

【问题讨论】:

    标签: c# linq list collections foreach


    【解决方案1】:

    你可以试试这个:

    foreach (var item in Results)
    {
        if (LookForMe.Any(x=>item.URL.Contains(x)) 
        {
            // then do something
        }
    }
    

    使用Any 扩展方法,您正在查看LookForMe 中是否存在任何世界,该世界包含在item.URL 中。如果是,则返回 true。否则,它返回 false。

    【讨论】:

    【解决方案2】:

    你的支票应该是:

    if(LookForMe.Contains(item.URL))
    

    如果item.URL 出现在列表LookForMe 中,这将返回true。

    但如果您尝试比较 URL 的任何部分与您列表中的任何项目匹配,那么您的检查应该是:

    if(LookForMe.Any(r=> item.URL.Contains(r)))
    

    【讨论】:

    • 如果你打算使用集合 Contains 方法,特别是如果集合中有很多条目,最好在定义 LookForMe 时调用 ToLookup geekswithblogs.net/BlackRabbitCoder/archive/2011/03/24/… 生成一个“索引”查找,而不是基本上调用包含时发生的扫描。然后,您检查查找结果是否为 null 以检查是否存在。
    • 欣赏两个 cmets。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2012-08-18
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多