Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq – Loop through list of strings and add results to var variable

I have my code sample below.

List<string> userIds = userAppService.GetUserIds()
    .Where(usr => usr.Status == "Active")
    .Select(u => u.User_Id)
    .ToList();

Now i would like loop through list of above UserId’s and add the result to var variable.

foreach(string str in userIds)
{
    var result = SLSDBContext.USER_HISTORY
        .Where(i => i.UserId == str)
        .Select(x => new 
        {
            x.UserId,
            x.LogCount,
            x.IsRegistered 
        });

    return this.Json(result)
}

The problem with above is i will not be able to access ‘result’ variale outside of foreach block.. If i am trying yo declare ‘result’ variable before foreach block i am not able to assign the type to it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any better way to get the desired result ?

I tried using Any() operator in Linq but i am not able to get the desired result.

var result = SLSDBContext.USER_HISTORY
    .Where(i => i.UserId.Contains(userIds))
    .Select(x => new 
    {
        x.UserId,
        x.LogCount,
        x.IsRegistered 
    });

>Solution :

You could use a Join:

var activeUsers = userAppService.GetUserIds()
    .Where(usr => usr.Status == "Active");
var result = from uh in SLSDBContext.USER_HISTORY
             join au in activeUsers
                 on uh.UserId equals au.User_Id
             select new {
                 uh.UserId,
                 uh.LogCount,
                 uh.IsRegistered 
             };    

return this.Json(result.ToList());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading