C# 在每个索引处对嵌套列表中的值求和
我有一个名为_DataCollection的C# 在每个索引处对嵌套列表中的值求和,c#,linq,list,nested,C#,Linq,List,Nested,我有一个名为_DataCollection的列表,其中每个嵌套列表的值数量相等。尽管是所有字符串,但嵌套列表中的值将是由字母数字字符、空字符串或货币值组成的字符串。比如说 _DataCollection[0] = {"tom", "abc", "$525.34", "$123"} _DataCollection[1] = {"dick", "xyz", "$100", "$234"} _DataCollection[2] = {"harry", "", "$250.01", "$40"} _Da
列表
,其中每个嵌套列表的值数量相等。尽管是所有字符串,但嵌套列表中的值将是由字母数字字符、空字符串或货币值组成的字符串。比如说
_DataCollection[0] = {"tom", "abc", "$525.34", "$123"}
_DataCollection[1] = {"dick", "xyz", "$100", "$234"}
_DataCollection[2] = {"harry", "", "$250.01", "$40"}
_DataCollection[2] = {"bob", "", "$250.01", ""}
我需要做的是找到一种方法,将所有嵌套列表中每个索引的所有值相加,并将其添加到列表中:
newSumList[0] = "N/A" since "tom" + "dick" + "harry" + "bob" can't be aggregated.
newSumList[1] = "N/A" since "abc" + "xyz" + "" + "" can't be aggregated.
newSumList[2] = "1125.36"
newSumList[3] = "397" even though the last value of the last nested list is "".
基本上,将每个索引的嵌套列表中的所有数值相加
我能想到的唯一方法是迭代这些数据并保持一个运行总数,但我想知道我是否可以使用LINQ或其他方法来完成它。List\u DataCollection=new List();
List<List<string>> _DataCollection=new List<List<string>>();
_DataCollection.Add( new List<string> {"tom", "abc", "$525.34", "$123"});
_DataCollection.Add( new List<string> {"dick", "xyz", "$100", "$234"});
_DataCollection.Add( new List<string> {"harry", "", "$250.01", "$40"});
_DataCollection.Add( new List<string> {"bob", "", "$250.01", ""});
List<string> newSumList = new List<string>();
for (int i = 0; i < _DataCollection.Count; i++)
{
decimal Sum = 0;
string CurrentSumList;
string Comment;
decimal amount = 0;
for (int j = 0; j < _DataCollection.Count; j++)
{
bool IsDecimalAmount=decimal.TryParse( _DataCollection[j][i].Replace('$','0'),out amount);
if (IsDecimalAmount)
{
Sum += amount;
}
else
{
Comment = "String";
}
}
CurrentSumList = Sum.ToString();
newSumList.Add(CurrentSumList);
}
_添加(新列表{“汤姆”、“abc”、“525.34美元”、“123美元”);
_添加(新列表{“迪克”、“xyz”、“100美元”、“234美元”);
_添加(新列表{“harry”、“”、“$250.01”、“$40”});
_添加(新列表{“bob”、“”、“$250.01”、“”});
List newSumList=新列表();
对于(int i=0;i<\u DataCollection.Count;i++)
{
十进制和=0;
字符串列表;
字符串注释;
小数金额=0;
对于(int j=0;j<\u DataCollection.Count;j++)
{
bool IsDecimalAmount=decimal.TryParse(_DataCollection[j][i].Replace('$','0'),out amount);
如果(IsDecimalAmount)
{
总和+=金额;
}
其他的
{
Comment=“String”;
}
}
CurrentSumList=Sum.ToString();
newSumList.Add(CurrentSumList);
}
我已经实现了这一点&它给了我结果。试试这个:-
decimal _temp =0;
int ListLength = _DataCollection.First().Count();
var query = _DataCollection.SelectMany(x => x).
Select((v, i) => new { Val = v, Index = i % ListLength })
.GroupBy(x => x.Index)
.Select(z => z.Sum(y => decimal.TryParse(y.Val,out _temp) ? _temp : 0));
工作。给你
var list = new List<List<string>>
{
new List<string> {"tom", "abc", "$525.34", "$123"},
new List<string> {"dick", "xyz", "$100", "$234"},
new List<string> {"harry", "", "$250.01", "$40"},
new List<string> {"bob", "", "$250.01", ""}
};
decimal num;
var itemsPerLine = list[0].Count; // 4
var res = list.SelectMany(line => line);
.Select((s, i) => new { Text = s, Index = i })
.GroupBy(i => i.Index % itemsPerLine) // transformed matrix here
.Select(g => g.Sum(i =>
decimal.TryParse(i.Text, NumberStyles.AllowCurrencySymbol |
NumberStyles.AllowDecimalPoint,
new CultureInfo("en-US"), out num)
? num : 0));
var list=新列表
{
新名单{“汤姆”、“abc”、“525.34美元”、“123美元”},
新名单{“迪克”、“xyz”、“100美元”、“234美元”},
新名单{“哈里”,“250.01美元”,“40美元”},
新列表{“bob”、“”、“$250.01”、“”}
};
十进制数;
var itemsPerLine=列表[0]。计数;//4.
var res=list.SelectMany(line=>line);
.Select((s,i)=>new{Text=s,Index=i})
.GroupBy(i=>i.Index%itemsPerLine)//此处转换矩阵
.选择(g=>g.Sum)(i=>
decimal.TryParse(即文本、数字样式、允许货币符号)
NumberStyles.AllowDecimalPoint,
新文化信息(“en-US”),out num)
数量:0);
当然,您可以通过更改NumberStyles标志和区域性信息来指定应识别为数字的内容。//将$value替换为value并删除所有非值字符串
// Replace $value with value and remove all non-value strings
var dollars = _DataCollection
.Select(l => l.Select(str => str.Contains('$') ? str.Split('$')[1] : string.Empty));
var newSumList = new List<double>();
// Add all values in a new list
for (int i = 0; i < _DataCollection[0].Count; i++)
{
double toAdd = 0;
foreach (var entry in dollars)
{
// If entry is a value, parse it, 0 otherwise
var value = entry.ElementAt(i) != string.Empty ? double.Parse(entry.ElementAt(i)) : 0;
toAdd = toAdd + value;
}
newSumList.Add(toAdd);
}
newSumList.ForEach(Console.WriteLine);
var$s=\u数据收集
.Select(l=>l.Select(str=>str.Contains(“$”)?str.Split(“$”)[1]:string.Empty));
var newSumList=新列表();
//在新列表中添加所有值
对于(int i=0;i<_数据收集[0]。计数;i++)
{
双toAdd=0;
foreach(以美元为单位的var条目)
{
//如果条目是值,则解析它,否则为0
var value=entry.ElementAt(i)!=string.Empty?double.Parse(entry.ElementAt(i)):0;
toAdd=toAdd+值;
}
newSumList.Add(toAdd);
}
newSumList.ForEach(Console.WriteLine);
或者,对于不需要使用GroupBy重新排列序列的不同方法:
var culture = new CultureInfo("en-US");
List<string> sums =
_DataCollection.Count == 0
? new List<string>()
: Enumerable.Range(0, _DataCollection.First().Count)
.Select(i => _DataCollection.Select(list => list[i])
.Select(s => { decimal val; return string.IsNullOrEmpty(s) ? (decimal?)0 : decimal.TryParse(s, NumberStyles.Currency, culture, out val) ? (decimal?)val : (decimal?)null; })
.Aggregate((decimal?)0, (sum, val) => sum + val))
.Select(sum => sum.HasValue ? sum.Value.ToString(culture) : "N/A")
.ToList();
var culture=new CultureInfo(“en-US”);
列出总数=
_DataCollection.Count==0
? 新名单()
:可枚举的.Range(0,_DataCollection.First().Count)
.Select(i=>_DataCollection.Select(list=>list[i])
.Select(s=>{decimal val;返回字符串.IsNullOrEmpty(s)?(decimal?)0:decimal.TryParse(s,NumberStyles.Currency,culture,out val)?(decimal?)val:(decimal?)null;})
.合计((十进制?)0,(总和,val)=>总和+val))
.Select(sum=>sum.HasValue?sum.Value.ToString(区域性):“不适用”)
.ToList();
无需多次迭代并支持空源代码列表
var list = new List<string[]>
{
new [] {"tom", "abc", "$525.34", "$123"},
new [] {"dick", "xyz", "$100", "$234"},
new [] {"harry", "", "$250.01", "$40"},
new [] {"bob", "", "$250.01", ""}
};
var cutlure = new CultureInfo("en-US");
var result = list.Aggregate((decimal[])null, (sums, strings) =>
{
if (sums == null)
sums = Enumerable.Repeat(decimal.MinValue, strings.Length).ToArray();
for (int i = 0; i < strings.Length; i++)
{
decimal value;
if (decimal.TryParse(strings[i], NumberStyles.Currency, cutlure, out value))
sums[i] = (sums[i] == decimal.MinValue) ? value : sums[i] + value;
}
return sums;
},
sums => sums.Select(sum => (sum == decimal.MinValue) ? "N/A" : sum.ToString()).ToArray());
var list=新列表
{
新[]{“汤姆”、“abc”、“525.34美元”、“123美元”},
新[]{“迪克”、“xyz”、“100美元”、“234美元”},
新[]{“哈里”,“250.01美元”,“40美元],
新[]{“bob”、“”、“$250.01”、“”
};
var cutlure=新文化信息(“美国”);
var result=list.Aggregate((十进制[])null,(总和,字符串)=>
{
如果(总和=null)
sums=可枚举的.Repeat(decimal.MinValue,strings.Length).ToArray();
for(int i=0;isums.Select(sum=>(sum==decimal.MinValue)?“N/A”:sum.ToString()).ToArray();