user517406
user517406

Reputation: 13763

LINQ adding to list object in loop

I have a situation where I need to populate a list object by looping through a loop of objects, check against a condition, and if the condition is met, add the item to my list. Currently I cannot find an example of the syntax required to add to the list rather than clear it and repopulate it each time the loop iterates to the next item. Can somebody help?

List<ProfileRightsJSON> prf = new List<ProfileRightsJSON>();

try
{
    for (int i = 0; i < lstProfiles.Count; i++)
    {
        prf = (from p in _database.tblProfileRights
               where p.fkProfileID ==
               lstProfiles[i].ProfileID
               select new ProfileRightsJSON
               {
                   FunctionID = p.fkFunctionID,
                   UserTypeID = p.fkUserTypeID,
                   RecursiveRights = p.RecursiveRights
               }).ToList();
    }

Upvotes: 0

Views: 3401

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503954

It looks like you really want something like this:

var profileIds = lstProfiles.Select(x => x.ProfileID).ToList();

var prf = (from p in _database.tblProfileRights
           where profileIds.Contains(p.fkProfileID)
           select new ProfileRightsJSON
           {
               FunctionID = p.fkFunctionID,
               UserTypeID = p.fkUserTypeID,
               RecursiveRights = p.RecursiveRights
           }).ToList();

Upvotes: 2

Related Questions