0

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 
    });
2
  • do you want to append the result of the current interation on every iteration, or replace the previous (because that's what you're currently doing)? Commented Dec 28, 2022 at 11:15
  • I'm almost sure you need Where(i => userIds.Contains(i.UserId)), not Where(i => i.UserId.contains(userIds)) Commented Dec 28, 2022 at 11:17

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.