C# 以下代码的linq查询是什么? 类程序 { 公共静态类布尔(字符串到搜索,字符串到查找) { if(toSearch.Contains(toFind)) 返回true; 其他的 返回false; } 静态void Main(字符串[]参数) { List str=新列表(); List strNew=新列表(); str.Add(“abdecacd”); str.Add(“facdgh”); str.Add(“iabcacdjk”); str.Add(“lmn”); str.Add(“opqe”); str.Add(“acbd”); str.Add(“efgh”); 字符串strToSearch=“acd、abc、abcacd、al”; 字符串[]desc=strToSearch.Split(','); 对于(int i=0;ix.Contains(y)).ToList();
如何为上面的代码编写linq查询,在这个strToSearch变量值将是动态的,用户将输入逗号分隔的值,用户可以根据需要输入任意多个逗号分隔的值,我想编写一个linq查询,它将在包含用户输入的值的列表中查找所有值。C# 以下代码的linq查询是什么? 类程序 { 公共静态类布尔(字符串到搜索,字符串到查找) { if(toSearch.Contains(toFind)) 返回true; 其他的 返回false; } 静态void Main(字符串[]参数) { List str=新列表(); List strNew=新列表(); str.Add(“abdecacd”); str.Add(“facdgh”); str.Add(“iabcacdjk”); str.Add(“lmn”); str.Add(“opqe”); str.Add(“acbd”); str.Add(“efgh”); 字符串strToSearch=“acd、abc、abcacd、al”; 字符串[]desc=strToSearch.Split(','); 对于(int i=0;ix.Contains(y)).ToList();,c#,linq,linq-to-sql,linq-to-entities,C#,Linq,Linq To Sql,Linq To Entities,如何为上面的代码编写linq查询,在这个strToSearch变量值将是动态的,用户将输入逗号分隔的值,用户可以根据需要输入任意多个逗号分隔的值,我想编写一个linq查询,它将在包含用户输入的值的列表中查找所有值。 我需要linq查询的原因,因为linq在我的应用程序中使用。请帮我解决这个问题。LINQ表达式是: class Program { public static bool Like(string toSearch,string toFind) { if
我需要linq查询的原因,因为linq在我的应用程序中使用。请帮我解决这个问题。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);
}
}
}
}
List strNew=str.Where(x=>desc.Any(y=>x.Contains(y)).ToList();
这甚至可以简化(针对.NET运行时而不是程序员简化)为:
List strNew=str.Where(x=>desc.Any(x.Contains)).ToList();
通过删除中间lambda函数
一般来说,你写的和我写的没有“速度”上的区别。这两个表达式都是O(m*n),其中m=
str.Length
和n=desc.Length
,所以O(x^2)。您没有进行精确搜索,因此无法使用通常的技巧创建HashSet
(或者在内部执行相同操作的str.Intersect(desc).ToList()
)这里有一个错误strNew
始终不是null,字符串上的ToString()
是no-opt如果(pred)返回true,则不执行;否则返回false代码>执行<代码>返回pred
我建议使用Like
方法,因为它允许更改搜索的含义(例如,使用Damerau–Levenshtein距离度量)。
List<string> strNew = str.Where(x => desc.Any(y => x.Contains(y))).ToList();
List<string> strNew = str.Where(x => desc.Any(x.Contains)).ToList();