在项目列表中查找索引 [英] find index in item list
问题描述
我有一个包含2列的表,第一个名字
,第二个expsup
,还有一个像这些:
i have a table with 2 colum , first name
, second expsup
, and also ia have a transactions like these :
a: 0.2,b: 0.3,c: 0.1
a: 0.4,c: 0.5
i可以拆分名称和浮点数( expsup
)并将它们放在变量(item.Name和item.Expsup)上,就像这样
a = item.Name 0.4 = item.Expsup
现在我想将它们插入表中并将所有expsups加在一起。(对于例子为第一个a:0.2读取并插入表中,对于第二个事务a:0.4将读取0.2和0.4加在一起)
i could split name and the float number (expsup
)and put them on variable (item.Name and item.Expsup) like this
"a = item.Name 0.4=item.Expsup"
now i want to insert them in table and all expsups add together.(for example for first one a: 0.2 read and insert in table , for second transaction that a: 0.4 will read 0.2 and 0.4 be add together)
private void AddItem(Item item)
{
var list = this.Items.Where(x => x.Name == item.Name).ToList();
if (list.Count == 0) // item doesnot exist in table
{
item.count = 1
item.Name = item.Name;
Expsup = item.Expsup;
this.Items.Add(item);
}
else if (list.Count == 1) //item exist in table
{
现在我必须在表中搜索以找到与当前项目具有相同名称的项目,然后挖掘项目的expsup然后添加它们(例如a:0.2插入表格和现在a:0.4读取,我们应该在表中搜索firs以找到最后的expsup并现在添加新的expsup)
now here i have to search in table to find item with same name with current item and then mining the item's expsup and then add them (for example a: 0.2 inserted in table and now a: 0.4 read , we should firs search in table to find last expsup and now add new expsup to it)
推荐答案
as Sergey Alexandrovich Kryukov [ ^ ]在这个论坛上多次提到: 你应该工作数据,而不是字符串表示!
为了能够得到项目的总和,你必须定义课程如下:
As Sergey Alexandrovich Kryukov[^] had mentioned several times on this forum: you should work on data, not on its string representation!
To be able to get the sum of items, you have to define class as follow:
public class Item
{
private int index = 0;
private string name = string.Empty;
private double expsup = 0.0;
public Item(int _index, string _name, double _expsup)
{
index= _index;
name = _name;
expsup = _expsup;
}
public int Index
{
get{return index;}
set{index = value;}
}
public string Name
{
get{return name;}
set{name = value;}
}
public double Expsup
{
get{return expsup;}
set{expsup = value;}
}
}
用法:
Usage:
List<string> stupiddata= new List<string>{"a: 0.2,b: 0.3,c: 0.1", "a: 0.4,c: 0.5"};
List<Item> items = stupiddata
.SelectMany(it=>it.Split(','))
.Select((it, ind)=>new Item
(
ind++,
it.Split(':')[0],
Convert.ToDouble(it.Split(':')[1].Trim(), new System.Globalization.CultureInfo("en-US"))
)).ToList();
var sumOfItems = items.GroupBy(it=>it.Name)
.Select(grp=>new
{
ItemName = grp.Key,
ItemSum = grp.Sum(a=>a.Expsup)
});
foreach(var v in sumOfItems)
{
Console.WriteLine("{0} : {1}", v.ItemName, v.ItemSum);
}
结果:
Result:
a : 0.6
b : 0.3
c : 0.6
这篇关于在项目列表中查找索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!