gpt4 book ai didi

c# - 更新列表列表中的属性

转载 作者:行者123 更新时间:2023-11-30 19:35:52 26 4
gpt4 key购买 nike

问题是:如何在不循环的情况下更新 allItems 中的字段 ItemCount(例如,使用 Linq)?例如,如果 Index = 0,我想将 ItemCount 设置为 ItemCount-5。

你可以看到下面的代码。

我有以下类(class):

public class Item
{
private int index;
private string item_name;
private double item_count;
private string type_name;

public int Index
{
get { return index; }
set { index = value; }
}
public string ItemName
{
get { return item_name; }
set { item_name = value; }
}
public double ItemCount
{
get { return item_count; }
set { item_count = value; }
}
public string TypeName
{
get { return type_name; }
set { type_name = value; }
}

}

public class CombMin
{
private double min_count;
private List<Item> combination;

public double MinCount
{
get { return min_count; }
set { min_count = value; }
}
public List<Item> Combination
{
get { return combination; }
set { combination = value; }
}
}

然后我创建了 List allItems:

        var item1 = new Item { Index=0,ItemName="x1",ItemCount=104,TypeName="Type1" };
var item2 = new Item { Index = 1, ItemName = "x2", ItemCount = 104, TypeName = "Type1" };
var item3 = new Item { Index = 2, ItemName = "x3", ItemCount = 1495, TypeName = "Type1" };
var item4 = new Item { Index = 0, ItemName = "x1", ItemCount = 104, TypeName = "Type1" };
var item5 = new Item { Index = 1, ItemName = "x2", ItemCount = 104, TypeName = "Type1" };
var item6 = new Item { Index = 2, ItemName = "x3", ItemCount = 1495, TypeName = "Type1" };

var items1 = new List<Item>();
var items2 = new List<Item>();
items1.Add(item1);
items1.Add(item2);
items1.Add(item3);

items2.Add(item4);
items2.Add(item5);
items2.Add(item6);

var allItems = new List<CombMin>();
allItems.Add(new CombMin { Combination = items1, MinCount = 104 });
allItems.Add(new CombMin { Combination = items2, MinCount = 104 });

问题是:如何在不循环的情况下更新 allItems 中的字段 ItemCount(使用 Linq)?例如,如果 Index = 0,我想将 ItemCount 设置为 ItemCount-5。

最佳答案

基本解决方案:

allItems.ForEach(x => x.Combination.FirstOrDefault(ele => ele.Index == 0).ItemCount -= 5);

As mentioned in comment if there is only 1 element with index 1 then you can do is :

   allItems.ForEach(x => x.Combination.First(ele => ele.Index == 0).ItemCount -= 5);

If you are not sure that the given index exists in the collection you can do is

CombMin element = new CombMin();
int index = 25;//does not exists in the collection
element = allItems.FirstOrDefault(x => x.Combination.Any(ele => ele.Index == index));
if (element != null)
element.Combination.FirstOrDefault(ele => ele.Index == index).ItemCount -= 5;

关于c# - 更新列表列表中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com