Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two Collection<T>

Tags:

c#

collections

I got a Function that returns a Collection<string>, and that calls itself recursively to eventually return one big Collection<string>.

Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection.

I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection, it can be pretty much any suitable data type.

Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ.

Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.

like image 737
Michael Stum Avatar asked Sep 11 '08 08:09

Michael Stum


People also ask

How do I merge two collections in power app?

Firstly, combine collection2 with collection1 by using the same code that collection1 and collection2 both have. Then collect the code that only collection2 has to the step1's collection.

What is merge in laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.

How to merge array in Collection laravel?

->concat() is a better solution on database collection merging. $allItems = new \Illuminate\Database\Eloquent\Collection; $allItems = $allItems->concat($collection1); $allItems = $allItems->concat($collection2); The reason for this is when merging they take ID of the table as the key.


1 Answers

If you're using List<> you can use .AddRange to add one list to the other list.

Or you can use yield return to combine lists on the fly like this:

public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2)
{
    foreach(string item in col1)
        yield return item;

    foreach(string item in col2)
        yield return item;
}
like image 162
Mendelt Avatar answered Oct 04 '22 15:10

Mendelt