[英]A better way to count and sort by frequency?
我有一個這樣的字符串liste
title1;duration1
title2;duration2
title1;duration3
這意味着title
顯示的duration
毫秒將被下一個title
替換為下一個duration
。
title
可以重復。
目標是查找每個相同的title
,然后添加其duration
,然后創建所有不同title
的列表,按它們的duration
之和降序排序。
我的做法:
string[] units = liste.split('\n');
Dictionary<string, long> d = new Dictionary<string, long>();
foreach(var row in units)
{
string[] e = row.split(';');
//if e[0] in d => add e[1] to d[e[0]] else set d[e[0]] to e[1]
}
//Convert d to list and sort descendingly by long.
有沒有更好的辦法?
我不一定建議這是最好的方法,因為它是一種難以理解且可維護的代碼很重要,但是您可以使用 LINQ 在單個語句中獲得結果。 此解決方案假定您對自己的數據是干凈的有信心 - 這意味着沒有空白值或不轉換為雙精度值的值等。
string liste = @"title1;8.91
title2; 3
title1; 4.5";
var result = liste.Split('\n')
.Select(l => new {
title = l.Substring(0, l.IndexOf(';')).Trim(),
duration = l.Substring(l.IndexOf(';')+1, l.Length - (l.IndexOf(';')+1)).Trim()
})
.GroupBy(l => l.title)
.Select(l => new { title = l.Key, durations = l.Sum(m => double.Parse(m.duration))})
.OrderByDescending(l => l.durations);
使用 linq:
string input = "title1;10\n" +
"title2;20\n" +
"title1;30";
var rows = input.Split(new char[] {'\n'}).Select(x => x.Split(new char[] {';'})).Select(y => new {title = y.First(), duration = int.Parse(y.Last())}).ToList();
var sums = rows.GroupBy(x=> x.title).Select(x => new {title = x.Key, duration = x.Sum(y => y.duration)}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.