本文介绍了更新列表列表中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题是:如何在没有循环的情况下更新allItems内部的ItemCount字段(例如,使用Linq)?例如,如果Index = 0,我想将ItemCount设置为ItemCount-5.
The question is: How can I update the field ItemCount inside allItems without loop (using Linq, for example)? For example, if Index = 0, I want to set ItemCount to ItemCount-5.
您可以看到下面的代码.
You can see the code below.
我有以下课程:
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:
Then I created 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.
The question is: How can I update the field ItemCount inside allItems without loop (using Linq)? For example, if Index = 0, I want to set ItemCount to ItemCount-5.
推荐答案
基本解决方案:
allItems.ForEach(x => x.Combination.FirstOrDefault(ele => ele.Index == 0).ItemCount -= 5);
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;
这篇关于更新列表列表中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!