开发者

LINQ adding to list object in loop

开发者 https://www.devze.com 2023-02-26 14:24 出处:网络
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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消