2012-09-26 30 views
0

我是ASP.NET C#的新手。嘗試創建一個ArrayList,其中兩列用於值(字符串),另一個用於統計每個列的數量。在添加值時,我需要搜索ArrayList以查找該值是否已經存在,如果是,則添加1,如果不是,則將其添加到數組並將count列設置爲1.有人可以提供一些代碼示例嗎?如果有更好的方法,那麼我想聽聽它。填充ArrayList 2列並保持在每個事件的第二列計數C#

回答

0

如果你剛剛開始的字符串列表,有很多簡單的方法來做到這一點。

我可能會在這裏

List<string> items = GetItems(); // from somewhere 
var groups = items.GroupBy(i => i); 

var countedItems = groups.Select(g => new 
    { Value = g.First(), HowMany = g.Count() }); 

使用GroupBy擴展,然後投入一個ArrayList,如果你想:

var arrayList = new ArrayList(); 
foreach (var thing in countedItems) 
{ 
    arrayList.Add(thing.Value + " " thing.HowMany); 
} 

但我可能更願意把這個變成一個Dictionary,因爲你知道每個單詞只會映射到一個值 - 它出現的次數。

var result = countedItems.ToDictionary(i => i.Value, i => i.HowMany); 
1
private static Dictionary<string, int> values = new Dictionary<string, int>(); 

private static void Add(string newValue) 
{ 
    if(values.ContainsKey(newValue)) 
    { 
     values[newValue]++; // Increment count of existing item 
    } 
    else 
    { 
     values.Add(newValue, 1); // Add new item with count 1 
    } 
}