2012-01-17 36 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