在c#中通过搜索更新对象的属性

本文关键字:更新 对象 属性 搜索 | 更新日期: 2023-09-27 18:01:54

我有一个数据结构如下:我有一个具有我想要搜索的属性的对象列表,然后当我找到与我的搜索查询匹配的所有对象时,我想为所有找到的对象更新另一个属性。下面是一个对象属性的例子:

Name: Sean Aston
City: Toronto
Eye Color: Blue
Warnings: 4
Name: Cole Anderson
City: New York City
Eye Color: Black
Warnings: 1
Name: Polly Smith
City: Toronto
Eye Color: Blue
Warnings: 3

我的搜索将是选择列表中属性颜色为蓝色和城市为多伦多的所有对象。它应该返回对象1和3。然后,我应该能够更新第一个和第三个对象的warnings属性,使其递增1。

我怎样才能做到这一点?

在c#中通过搜索更新对象的属性

要匹配您的确切请求,应该是这样的:

foreach (var item in MyObjectList.Where(o => o.EyeColor == "Blue" && o.City == "Toronto"))
{
    item.Warnings ++;
}

但是我怀疑这些标准完全是由用户决定的,所以你不知道你在编译时像这样寻找什么。在这种情况下:

var search = (IEnumerable<MyObject>)MyObjectList;
if (!string.IsNullOrEmpty(txtCity.Text))
{
    search = search.Where(o => o.City == txtCity.Text);
}
if (!string.IsNullOrEmpty(txtEyeColor.Text))
{
    search = search.Where(o => o.EyeColor == txtEyeColor.Text);
}
// similar checks for name or warning level could go here
foreach(var item in search) {item.Warnings++;}

这个怎么样

People.Where(p => p.EyeColor == "blue" && p.City == "Toronto")
      .ToList().ForEach(p => p.Warnings++);

假设您有一个IEnumerable<YourType>(数组、列表等),您将这样做:

var filtered = yourlist.Where(o => o.EyeColor == "Blue" && o.City =="Toronto")
foreach(item in filtered)
{
    item.Warnings++;
}