问题是:如何在没有循环的情况下更新allItems内部的ItemCount字段(例如,使用Linq)?例如,如果Index = 0,我想将ItemCount设置为ItemCount-5。
您可以在下面看到代码。
我有以下课程:
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 });
问题是:如何在没有循环的情况下(使用Linq)更新allItems内的ItemCount字段?例如,如果Index = 0,我想将ItemCount设置为ItemCount-5。
最佳答案
基本解决方案:
allItems.ForEach(x => x.Combination.FirstOrDefault(ele => ele.Index == 0).ItemCount -= 5);
如评论中所述,如果只有1个元素的索引为1,那么您可以执行以下操作:
allItems.ForEach(x => x.Combination.First(ele => ele.Index == 0).ItemCount -= 5);
如果不确定给定索引是否存在于集合中,则可以执行以下操作:
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;