在linq查询结果中使用foreach的问题
我的 linq 查询如下:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
我想循环遍历列表中的每个值<>
我尝试使用 foreach 来完成此任务。这是愚蠢的我无法弄清楚
我正在使用这样的东西
foreach (List<string> item in result)
{
if (item.ToString() == userName)
{
userExistsFlag = 1;
}
}
但是.net编译器只是吓坏了:
并给我这些错误
无法隐式地将类型'System.Collections.Generic.List'转换为'System .Collections.Generic.List'
无法将类型“AnonymousType#1”转换为“System.Collections” .Generic.List'
感谢您
对所有这些实现的预期,其中哪一个是最有效且消耗更少资源的。 如果有人能为我澄清这一点,那就太好了。
I have linq query as follows:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
i want to loop through each value in the list<>
I tried to use the foreach to accomplish this. It is stupid i could not figure it out
I'm using something like this
foreach (List<string> item in result)
{
if (item.ToString() == userName)
{
userExistsFlag = 1;
}
}
But the .net compiler is just freaking out:
and giving me these errors
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
Cannot convert type 'AnonymousType#1' to 'System.Collections.Generic.List'
Thanks in anticipation
OF ALL THESE IMPLEMENTATIONS WHICH ONE IS MOST EFFICIENT AND CONSUMES LESS RESOURCES.
IT WOULD BE KIND ENOUGH IF SOME ONE CAN CLARIFY THIS FOR ME.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 Linq 更短:
正如其他答案中所建议的,您不需要投影到匿名类型:
编辑:
最有效的 - 如果您不需要用户名集 - 是查询DB 直接检查用户名是否存在,因此
感谢 @Chris Shaffer 的评论和 @Cybernatet 的回答 - 他就快到了。我建议你接受他的答案但使用 Any() ;-)
Shorter using Linq:
As suggested in the other answers you do not need to project to an anonymous type:
Edit:
The most efficient - if you do not need the set of user names otherwise - is to query the DB directly to check whether the user name exists, so
Credit goes to @Chris Shaffer in the comments and @Cybernatet's answer - he was almost there. I would suggest you accept his answer but use Any() ;-)
尝试:
Try:
如果您的查询返回名称列表,则您的 FOREACH 循环应如下所示
If your query returns a list of names, your FOREACH loop should look like this
跳过使用
new { userNameList = cust.UserName }
这使其成为匿名实例。你可以尝试Skip using
new { userNameList = cust.UserName }
which is making it an anonymous instance. You can try如果您只是获取一个属性并想要一个字符串列表,则没有理由使用匿名类型。代码应该像这样工作:
if you're just getting the one property and want a list of strings there is no reason to use an anonymous type. code should work like this: