Home > front end >  Linq - Loop through list of strings and add results to var variable
Linq - Loop through list of strings and add results to var variable

Time:12-29

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.

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 
    });

CodePudding user response:

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());

CodePudding user response:

you can initialize the result before loop and use Concat method.

var result = Enumerable.Empty<USER_HISTORY>();

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

return this.Json(result);
  • Related