【问题标题】:I want to remove specific property from list not whole elements我想从列表中删除特定属性而不是整个元素
【发布时间】:2017-07-30 02:02:49
【问题描述】:

请在这里提供帮助。下面是我的课:

public class UserGroup : Result
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
}

我有 UserGroup 类的列表类型,我试图从列表中删除 UserId 和 GroupId 属性,只要我得到这两个属性的 0 值,但是它会删除整个特定类元素以及结果类属性。我想要错误标记在输出中它不应该删除。以下是我的输出:

<EditGroupMembershipResult>
            <UserGroup>
                <Error>
                    <string>User does not exist</string>
                    <string>User group does not exist</string>
                </Error>
                <UserId>0</UserId>
                <GroupId>0</GroupId>
            </UserGroup>
        </EditGroupMembershipResult>

【问题讨论】:

  • “我希望输出中的错误标签不应该删除” - 我完全不清楚你的意思是什么......你展示的是 XML,而不是列表......而且您还没有显示做错事的代码。请提供minimal reproducible example
  • 你能详细说明你的问题吗?
  • 这是我的 Web 服务功能之一,我从邮递员那里调用此 Web 服务,这就是我在输出中以 xml 格式获取列表的原因。当我试图从列表中删除 0 时,它正在删除 用户不存在用户组不存在。作为参考,我将图片上传到:screencast.com/t/GdAPW7APxull

标签: list c#-4.0


【解决方案1】:

您可以使用列表中的 ToArray() 来删除特定项目:

  List<UserGroup > userGroups = new List<UserGroup >();
    //Add Item to your List Here.
    foreach (string item in userGroups.ToArray())
    {
        if (item == "UserId" || item == "GroupId")
          {
            userGroups.Remove(item);
          }
    }

【讨论】:

  • 这就是“strings.Remove(item);”的意思你不会得到任何 strings.remove() 方法:(
  • @Nimeshkhatri,好点!我刚刚编辑了代码。谢谢指正。
  • 它显示编译时错误。供参考:screencast.com/t/6nOnJQzUP6
猜你喜欢
  • 2016-06-17
  • 2022-11-14
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2015-05-13
相关资源
最近更新 更多