2012-01-17 34 views
1

我有6個數組列表,我想知道哪一個是最長的,而不使用一堆IF語句。比較多個arraylist長度找到最長的一個

「if arraylistist.count> anotherlist.count Then ....」< - 反正這樣做不是這樣嗎?

在VB.net或C#.Net(4.0)中的例子會很有幫助。

arraylist1.count 
arraylist2.count 
arraylist3.count 
arraylist4.count 
arraylist5.count 
arraylist6.count 

DIM longest As integer = .... 'the longest arraylist should be stored in this variable. 

感謝

+0

vb.net or c#?.. – 2012-01-17 14:05:43

+0

您使用的是什麼版本的.NET,什麼是* exact *類型? (示例代碼會很好...) – 2012-01-17 14:05:57

+0

4.0。 c#.net或vb.net的例子很好 – tdjfdjdj 2012-01-17 14:06:54

回答

2

是1個if聲明接受嗎?

public ArrayList FindLongest(params ArrayList[] lists) 
{ 
    var longest = lists[0]; 
    for(var i=1;i<lists.Length;i++) 
    { 
     if(lists[i].Length > longest.Length) 
      longest = lists[i]; 
    } 
    return longest; 
} 
0
SortedList sl=new SortedList(); 
foreach (ArrayList al in YouArrayLists) 
{ 
    int c=al.Count; 
    if (!sl.ContainsKey(c)) sl.Add(c,al); 
} 
ArrayList LongestList=(ArrayList)sl.GetByIndex(sl.Count-1); 
+0

你的意思是'foreach'嗎? 「Count」也必須以大寫字母「C」開頭。 – Nuffin 2012-01-17 14:17:54

+0

@Tobias謝謝,修復 – 2012-01-17 14:21:02

2

你可以使用Linq:如果您存儲的一切

public static int FindLongestLength(params ArrayList[] lists) 
{ 
    return lists == null 
     ? -1 // here you could also return (int?)null, 
      // all you need to do is adjusting the return type 
     : lists.Max(x => x.Count); 
} 
0

public static ArrayList FindLongest(params ArrayList[] lists) 
{ 
    return lists == null 
     ? null 
     : lists.OrderByDescending(x => x.Count).FirstOrDefault(); 
} 

如果你只是想在長度最長的名單,這是更簡單在列表列表中,例如

List<List<int>> f = new List<List<int>>(); 

然後,像

List<int> myLongest = f.OrderBy(x => x.Count).Last(); 

一個LINQ將產生數最多的項目清單。當然,你將不得不處理的情況時有扎最長列表

0

如果你只是想最長的ArrayList的長度:

public int FindLongest(params ArrayList[] lists) 
{ 
    return lists.Max(item => item.Count); 
} 

或者,如果你不想寫一個函數並且只想內聯代碼,那麼:

int longestLength = (new ArrayList[] { arraylist1, arraylist2, arraylist3, 
    arraylist4, arraylist5, arraylist6 }).Max(item => item.Count); 
+0

項目不會出現intellisence。有我需要的參考嗎? – tdjfdjdj 2012-01-17 15:06:43

+0

您將需要添加'使用System.Linq;' – 2012-01-17 15:25:16