2017-08-28 53 views
-1

的多個列表我有一個父列表像這樣: -分割清單按值C#

ParentList = {a,b,c,a,c,d,b,a,c,c} 

我想這個名單分割成較小的名單是這樣的: -

ListA = {a,a,a} ListB = {b,b} ListC= {c,c,c,c} ListD = {d} 

我主要意圖是獲得最高發生值的計數。在上面的情況下,它將是4這是ListC的計數。

如何將父列表分成小列表,如示例中所述。或者有沒有一種方法可以在沒有列表分割的情況下獲得最大的計數。

任何幫助表示讚賞。

+2

你試過什麼嗎? Linq GroupBy? –

+0

@GiladGreen我已經嘗試循環瀏覽父列表並創建不同的列表。但是看起來有點亂。 Linq – user3034944

+2

然後請發佈你已經嘗試過的..否則它看起來像一個「寫我的代碼」問題 –

回答

0

組假設你只想計數,而不是哪一個字符/字符串給出計數,這裏是一個襯墊(你需要using System.Linq;

var highestCount = ParentList.GroupBy(p => p).Max(p => p.Count()); 
2

使用GroupBy將類似的值,然後計算項目中的每一組中的用量:

var result = ParentList.GroupBy(item => item) 
         .Select(group => new { 
          Key = group.Key, 
          Count = group.Count() }) 
         .OrderByDescending(item => item.Count); 

您還可以使用查詢語法:

var result = from item in ParentList 
      group 1 by item into g 
      order by g.Count() descending 
      select new { Key = g.Key, Count = g.Count() }; 

如果你真的想用不同的不同的收藏變量給他們,就像你在上面的描述那麼你需要從代碼片段中檢索每個集合。您也可以對分組的結果使用ToDictionary

0
string maxRepeated = ParentList.GroupBy(s => s) 
        .OrderByDescending(s => s.Count()) 
        .First().Key; 
0

一個簡單的方法來做到這將使用LINQ

var chars = new[] { 'a', 'b', 'c', 'a', 'c', 'd', 'b', 'a', 'c', 'c' }; 
var largetstGroup = chars 
    .GroupBy(_ => _) // Group items by the letter this will yield groups (aka lists) that will conatin only each letter 
    .OrderByDescending(_ => _.Count()) //Order by the items in each list 
    .FirstOrDefault(); // get the first one 

如果你在你的列表,其中的GroupBy方法用於您可以指定任何財產進行分組更復雜的對象(例如,對於人的名單,你可以按年齡GroupBy(_=> _.Age)