使用Linq在IEnumerable的string []中搜索字符串 [英] Search for a string within the string[] of IEnumerable using Linq

查看:94
本文介绍了使用Linq在IEnumerable的string []中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从制表符分隔的平面文件中读取记录,并将其存储在

I''m reading in records from a tab-delimited flat-file, and storing those in a

IEnumerable<string[]>

请注意,它们是大量记录.

我想使用Linq快速遍历IEnumerable记录,但是当我在数组的值之一内找到一个值时,返回整个string []数组.
现状(可以,但是有点慢):

Please note that they''re are a large amount of records.

I want to use Linq to traverse through the IEnumerable records quickly, but return the whole string[] array when I find a value within one of the values of the array.

Current Situation (works fine but a little slow):

private IEnumerable<string[]> customers = GetCustomersFromCache();

foreach (string[] customer in customers)
{
    var strFound = Array.FindAll(customer, str => str.ToLower().Contains(searchText.Text.ToLower()));

    foreach (string record in strFound)
    {
      //doing stuff here with string array
    }
}


因此,目前我正在遍历每个客户记录,然后遍历每个客户记录.然后我可以获取客户数组的任何部分,并使用其''数据.

因此,可以使用Linq来查看IEnumerable中的string [],确定数组的任何部分是否包含我正在搜索的字符串,最后返回整个数组吗?

这意味着基本上要执行以下1 Linq命令:


So currently I''m looping through each Customers record, and then looping through each customer record. I can then grab any part of the customer array, and use its'' data.

So can Linq be used to look at the string[] within the IEnumerable, determine if any part of the array contains the string I''m searching for, and finally return the whole array?

Which means basically making the following 1 Linq command:

foreach (string[] customer in customers)
{
    var strFound = Array.FindAll(customer, str => str.ToLower().Contains(searchText.Text.ToLower()));
}

推荐答案

这会做什么吗?

Would this do what you want?

customers.Where(c => Array.FindAll(c, str => str.ToLower().Contains(searchText.Text.ToLower())).Count() > 0);



我不知道它的效果是否更好.


这可能会更快一些,因为它只查找第一个匹配项,足以告诉您是否有任何匹配项:



I don''t know if it performs any better though.


This is probably a little faster, as it only looks for the first match, enough to tell you if anything is there:

customers.Where(c => !String.IsNullOrEmpty(Array.Find(c, str => str.ToLower().Contains(searchText.Text.ToLower()))));


这比解决方案要好1:
This would be better than solution 1:
customers.Where(c => Array.FindAll(c, str => str.ToLower().Contains(searchText.Text.ToLower())).Any());



一旦找到第一个,这将停止搜索.



This will stop the search once the first is found.


这篇关于使用Linq在IEnumerable的string []中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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