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.
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() 😉