LINQ 在循环中添加到列表对象

发布于 2024-11-02 03:08:16 字数 651 浏览 0 评论 0原文

我遇到一种情况,我需要通过循环对象循环来填充列表对象,检查条件,如果满足条件,则将项目添加到我的列表中。目前,我找不到添加到列表所需的语法示例,而不是在每次循环迭代到下一项时清除它并重新填充它。有人可以帮忙吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很糊涂小朋友 2024-11-09 03:08:16

看起来您真的想要这样的东西:

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

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文