如何解决以下代码的 linq 查询是什么?
class Program
{
public static bool Like(string toSearch,string toFind)
{
if (toSearch.Contains(toFind))
return true;
else
return false;
}
static void Main(string[] args)
{
List<string> str = new List<string>();
List<string> strNew = new List<string>();
str.Add("abdecacd");
str.Add("facdgh");
str.Add("iabcacdjk");
str.Add("lmn");
str.Add("opqe");
str.Add("acbd");
str.Add("efgh");
string strToSearch= "acd,abc,abcacd,al";
string[] desc = strToSearch.Split(',');
for(int i = 0; i < str.Count; i++)
{
for(int j = 0; j < desc.Length; j++)
{
if(Like(str[i].ToString(),desc[j].ToString()))
{
strNew.Add(str[i].ToString());
break;
}
}
}
if(strNew != null)
{
foreach(string strPrint in strNew)
{
Console.WriteLine(strPrint);
}
}
}
}
如何为上述代码编写 linq 查询,在此 strToSearch 变量值将是动态的,用户将输入逗号分隔值,用户可以输入任意数量的逗号分隔值,我想编写一个 linq 查询,它将在 List 中查找包含用户输入的值的所有值。 我需要 linq 查询的原因,因为我的应用程序中使用了 linq。请帮我解决这个问题。
解决方法
LINQ 表达式为:
List<string> strNew = str.Where(x => desc.Any(y => x.Contains(y))).ToList();
甚至可以简化(简化为 .NET 运行时,而不是程序员):
List<string> strNew = str.Where(x => desc.Any(x.Contains)).ToList();
通过删除中间 lambda 函数。
总的来说,你写的和我写的没有“速度”差异。两个表达式都是 O(m*n),其中 m = str.Length
和 n = desc.Length
,所以 O(x^2)。您没有进行精确搜索,因此您不能使用创建 HashSet<string>
(或在内部执行相同操作的 str.Intersect(desc).ToList()
)的常用技巧。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。