C# Linq不工作
我使用以下代码过滤包含字符串pre的列表。 我错过了什么? 这是密码C# Linq不工作,c#,linq,C#,Linq,我使用以下代码过滤包含字符串pre的列表。 我错过了什么? 这是密码 string pre = "a"; List<string> A = new List<string>(); List<string> B = new List<string>(); DAL dal = new DAL(); A = dal.GetNames(); B = (from x in A where A.Contains(pre) select x)
string pre = "a";
List<string> A = new List<string>();
List<string> B = new List<string>();
DAL dal = new DAL();
A = dal.GetNames();
B = (from x in A
where A.Contains(pre)
select x).ToList();
B = A.Where(c => A.Contains(pre)).ToList();
string pre=“a”;
列表A=新列表();
列表B=新列表();
DAL=新的DAL();
A=dal.GetNames();
B=(从A中的x开始)
其中A.Contains(pre)
选择x).ToList();
B=A,其中(c=>A.Contains(pre)).ToList();
B在这里总是空的(在这两种情况下)。我想你要做的是找到列表中包含单词pre的所有项目? 在这种情况下,应改变这一点:
B = (from x in A
where A.Contains(pre)
select x).ToList();
进入
当列表中的pre完全匹配时,Linq查询仅返回非空结果将查询更改为:
B = (from x in A
where x.IndexOf(pre, StringComparison.CurrentCultureIgnoreCase) != -1
select x).ToList();
您的代码无法按预期工作,原因有二
pre
)匹配每个列表条目的任何子字符串,但您当前正在搜索每个条目上的精确匹配项。因此,当前代码不返回任何内容,因为列表A
不包含任何仅为“A”的字符串A
的整个实例,而不是正在计算的A
的当前条目Contains
,请使用IndexOf
评估列表中的每个字符串,这样就不需要精确匹配,只需在列表中每个字符串的任何位置查找搜索条件的任何匹配项
要修复2),请理解在lambda表达式中,左侧的变量是指正在迭代的当前项。因此,给定一个1,2,3,4,5的列表x
,如果我的表达式是n=>n>2
,这意味着在迭代中该表达式被计算5次,n
是1,2,3,4或5。在每个数字上,表达式都是n>2?进行评估,从而为列表中的每个条目生成真值或假值。在您的代码中,您没有使用引用表达式中正在迭代的当前列表项的变量,因此计算与当前条目无关-所有计算都将返回相同的结果,例如,如果我将原始表达式更改为n=>2>1
,对于此表达式,列表中的所有项的计算结果均为true
解决这个问题很简单,如其他答案所示-在表达式中,使用lambda表达式左侧的变量,而不是引用位于另一个范围之外的列表
string pre = "a";
List<string> A = new List<string>();
List<string> B = new List<string>();
A = new List<string>() { "a", "ba", "bb", "bc" };
B = (from x in A
where x.IndexOf(pre) > -1
select x).ToList();
B = A.Where(c => c.IndexOf(pre) > -1).ToList();
string pre=“a”;
列表A=新列表();
列表B=新列表();
A=新列表({“A”、“ba”、“bb”、“bc”});
B=(从A中的x开始)
其中x.IndexOf(pre)>-1
选择x).ToList();
B=A.Where(c=>c.IndexOf(pre)>-1.ToList();
string pre = "a";
List<string> A = new List<string>();
List<string> B = new List<string>();
A = new List<string>() { "a", "ba", "bb", "bc" };
B = (from x in A
where x.IndexOf(pre) > -1
select x).ToList();
B = A.Where(c => c.IndexOf(pre) > -1).ToList();