TomF
TomF

Reputation: 98

Merge Lists and "merge" sorting

I have a List of List's that I'm trying to figure out how to merge them into one unqiue list, except I also want to take into account the sorting of each list currently.

Ex:

List<List<string>> ListofLists = new List<List<string>>();
ListofLists.Add(new List<string>() { "Color", "Size", "Dimensions" });
ListofLists.Add(new List<string>() { "Color", "Size", "Dimensions" });
ListofLists.Add(new List<string>() { "Color", "Size", "Weight", "Dimensions" });

I want the contents of the "merged" list to be:

Color, Size, Weight, Dimensions

I've looked Unions but this adds "Weight" to the end of the list -- I want it to "merge" the lists keeping the "extra" values inline (as much as possible).

I also found this thread which is close but it seems to insert the 'extra' value at a random point.

Sorry if this isn't explained well, I don't really know how to describe this.

Edit: The goal of this is to place multiple products on a single table and list their specs beneath, showing similar specs on the same row. Some products might have different specs but for the most part they are the same.

So I'm trying to generate a single list of the possible Spec names to show in the first column. Typically the specs at the end are related to warranty, at the top related to models, etc. So if Product 3 has some weird spec I would rather have it inserted inline somewhere than tacked on the end under warranty.

Example output:

Model #    | 123 | 456 | 789
Color      | red | red | blue
Size       | big | big | small
Weight     |     |     | 3
Dimensions | 1"  | 1"  | 1"x1"x1"
Warranty   | 1   | 2   | 3

Probably not the best example, but for instance maybe 123 and 456 don't have a Weight spec. So rather than tack Weight on at the bottom (which is happening when I do a Union) I'd like it to be as close to "inline" with it's original list as possible. You can't see in this example but each product might have 30 specs, so it's desirable to have the important ones on top as their List of Specs reflects.

Upvotes: 2

Views: 457

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

Take a look at the LINQ Concat and Distinct extension methods. They should be able to help you accomplish what you're after.

Upvotes: 0

Neil
Neil

Reputation: 55402

Create a graph of the ordering of each of the elements in the lists. (So for ACDEFGHJ, ABDFGHIJ, ABCDEGIJ you would get A->C, A->B, C->D, B->D, B->C, etc.) Hopefully only one node will have no inward arcs (in this case A); add this element to your resulting list. Remove that node and its outward arcs, and repeat the process. If you have multiple nodes with no inward arcs, then you can choose one at random. If you have no nodes with no inward arcs, then you have a cycle. You could break the cycle by choosing a member at random, but you would have to find the cycle first...

Upvotes: 2

Related Questions