简体   繁体   中英

problem using foreach in linq query result

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

  1. Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

  2. 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:

bool userExistsFlag  = result.Any( x=> x.userNameList  == userName);

As suggested in the other answers you do not need to project to an anonymous type:

var userNames = (from Customer cust in db select cust.UserName).ToList();
bool userExists = userNames.Contains(userName);

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

 bool userExists = db.Any( x => x.UserName == userName);

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:

var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
userExistsFlag = result.Where(a=> a.userNameList == userName).Count() > 0;

or

userExistsFlag = (
                    from Customer cust in db 
                    where cust.UserName = userName
                    select cust
                 ).Count() > 0;

If your query returns a list of names, your FOREACH loop should look like this

foreach( String name in results ){
  ...
}

Skip using new { userNameList = cust.UserName } which is making it an anonymous instance. You can try

var result = (from Customer cust in db select cust.UserName ).ToList();

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:

var result = (from Customer cust in db select cust.UserName).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM