簡體   English   中英

一種更好的按頻率計數和排序的方法?

[英]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 在單個語句中獲得結果。 此解決方案假定您對自己的數據是干凈的有信心 - 這意味着沒有空白值或不轉換為雙精度值的值等。

  1. 在換行符上拆分字符串
  2. 將 object 和 substring 投影在“;”
  3. 按標題分組
  4. 再次投影到一個匯總分組的新列表中
  5. 最后對列表進行排序。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM