简体   繁体   English

如何在C#中编辑/更新集合中的数据

[英]How to Edit/Update Data in Collection in C#

I have a collection in my C# code 我的C#代码中有一个集合

private ObservableCollection<UserForms> _userForms = 
    new ObservableCollection<UserForms>();

public ObservableCollection<UserForms> UserForms { get { return _userForms; } }

I am filling collection with 4 values 我正在用4个值填充收藏

foreach (DataRow dr in DataTable.Rows)
{
                    UserForms.Add(new UserForms()
                    {
                        FormID = Convert.ToInt32(dr["FormID"]),
                        FormName = dr["FormName"].ToString(),
                        FromSyName = dr["FormSyName"].ToString(),
                        Visibility = false,
                        RoleAdd=false,
                        RoleEdit=false,
                        RoleDelete=false
                    });
}

I am filling this in Form_Load() event 我在Form_Load()事件中填写此内容

Now I want to update 现在我要更新

Visibility = true,
RoleAdd=true,
RoleEdit=true,
RoleDelete=true

in specified row in the collection. 在集合中的指定行中。

You simply need to do the following: 您只需要执行以下操作:

UserForms[0].Visibility = true;

where "[0]" is the index. 其中“ [0]”是索引。

If your ObservableCollection is enumerable (which collections usually are) you can use a foreach loop as follows: 如果您的ObservableCollection是可枚举的(通常是哪个集合),则可以使用如下所示的foreach循环:

foreach(UserForms uf in UserForms)
{
    if (uf.FormID > 10)
        uf.Visibility = true;
}

In the above code, I change the visibility of rows which their FormID is higher than 10. 在上面的代码中,我更改了FormID大于10的行的可见性。

Looks like you need filter out some items and then update them. 看起来您需要过滤掉一些项目然后进行更新。

foreach(UserForms uf in UserForms.Where(i=>i.FormName == "FormName"/*put your filtering criteria here*/))
{
    uf.Visibility = true;
    // Set all needed properties here
}

You want to access the instance of collection. 您要访问集合的实例。

_userForms.ToList().ForEach((f) => f.Visibility = true); 

or if you know the index and want to update individual item. 或者,如果您知道索引并想更新单个项目。

 _userForms[index].Visibility = true;

or for multiple filter items 或用于多个过滤器项目

 var filterColl = coll.Where((c)=> c.FormName.StartsWith("A"));
 filterColl.ToList().ForEach((f) => f.Visibility = true); 

hope this helps.. 希望这可以帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM