问题
I am trying to extract the values shared by two arraylist into another arraylist.
using System.Linq;
private ArrayList GetSameOf2AL(ArrayList first, ArrayList second)
{
ArrayList same = new ArrayList();
var one = from int i in first select i;
var two = from int i in second select i;
var SameVal = one.Intersect(two);
//I am supposed to convert or cast SameVal into arraylist here
return same;
}
My questions are:
- I couldn't convert the
var
type back intoarraylist
, can someone advise me how? - Did I choose a wrong method to do this at the first place? Your advise is appreciated.
Thank you all for your kind attention =)
回答1:
List<int> intersection = first.Cast<int>().Intersect(second.Cast<int>()).ToList();
or
ArrayList intersection = new ArrayList();
foreach (var i in first.Cast<int>().Intersect(second.Cast<int>()))
intersection.Add(i);
回答2:
Since you are dealing with legacy code you can just use a simple foreach
loop:
private ArrayList GetSameOf2AL(ArrayList first, ArrayList second)
{
ArrayList same = new ArrayList();
var one = from int i in first select i;
var two = from int i in second select i;
var sameVal = one.Intersect(two);
//I am supposed to convert or cast SameVal into arraylist here
foreach (int i in sameVal)
same.Add(i);
return same;
}
This is really patchwork though, it would be much preferable to refactor your code to use List<int>
instead of ArrayList
- the effort shouldn't be too much and it will pay off immediately.
回答3:
First of all, ArrayList is an outdated collection that was used before Generics was introduced to .NET. You should not use it unless you're building legacy code. Instead you should turn your attention towards the List class.
IEnumerable<int> first = new []{1,2,3};
IEnumerable<int> second = new [] {2,3,4};
List<int> intersection = first.Intersect(second).ToList(); // result {2,3}
If you are in legacy mode then generics won't be available to you, and you will have to manually iterate the lists to find the intersection.
回答4:
This is a time when using the var
keyword as a shortcut to explicitly writing out the type can run you into trouble. If you had checked the return of the Intersect
LINQ extension, you'd see that the return is an IEnumerable<int>
. You can use some of the IEnumerable
extension methods to transfer the data represented by the IEnumerable
to an ArrayList
:
private ArrayList GetSameOf2AL(ArrayList first, ArrayList second)
{
ArrayList same = new ArrayList();
var one = from int i in first select i;
var two = from int i in second select i;
same.AddRange(one.Intersect(two).ToArray<int>());
return same;
}
来源:https://stackoverflow.com/questions/9900181/find-same-values-between-2-arraylist-and-return-as-another-arraylist