views:

68

answers:

2

Take these two lists:

List 1

Red Green Blue

List 2

Brown Red Blue Purple Orange

I'm looking for a way to combine these lists together to produce:

List 3

Brown Red Green Blue Purple Orange

I think the basic rules are these:

1) Insert on top the list any row falling before the first common row (e.g., Brown comes before the first common row, Red);

2) Insert items between rows if both lists have two items (e.g., List 1 inserts Green between Red and Blue); and

3) Insert rows on the bottom if the there's no "between-ness" found in 2 (e.g., List 2 inserts Orange at the bottom).

The lists are stored in a DataTable. I'm guessing I'll have to switch between them while iterating, but I'm having a hard time figuring out a method of combining the rows.

Thanks for any help.

--Brent

A: 

If you want to join two standard lists and did not care about the sort, you can use something like this:

var list1 = new[] { "Red", "Green", "Blue" };
var list2 = new[] { "Brown", "Red", "Blue", "Purple", "Orange" };

var result = new List<string>( list2 );
result.AddRange( list1.Except( list2 ) );

Trying to maintain some special order will be difficult. For example, Suppose list2 did not contain Red, what should the first item be: Brown or Red? Suppose that list1 has Yellow last but list2 has Yellow second. What should the order be?

If you are trying to merge two DataTables, there is a Merge method on a DataTable which lets you combine one DataTable into another.

DataTable.Merge

Thomas
+1  A: 

I think something along these lines should do it for you:

Dictionary<string, float> clrs = new Dictionary<string, float>();

float i = 0;
foreach (string s in largeList)
    clrs.Add(s, i++);

float lastIndex = 0;
for (int j = 0; j < smallList.Count; j++)
{
    if (largeList.Contains(smallList[j]))
        lastIndex = clrs[smallList[j]];
    else
        clrs.Add(smallList[j], lastIndex + 0.5f);
}

var sorted = from c in clrs.Keys orderby clrs[c] select c;

return sorted.ToList<string>();

it assumes no duplicates in either list and that the function is passed the larger list as largelist.

SnOrfus