How to "alternate" two data tables

Take these two lists:

List 1

Red green blue

List 2

Brown Red Blue Purple Orange

I am looking for a way to combine these lists together to create:

List 3

Brown Red Green Blue Purple Orange

I think the basic rules are as follows:

1) Insert at the top the list of any line falling before the first common line (for example, Brown comes before the first common line, Red);

2) Insert items between the lines if both lists have two items (for example, in list 1, a green color is inserted between red and blue); and

3) Insert the lines at the bottom if there is no โ€œgapโ€ between them (for example, in list 2, the orange is inserted at the bottom).

Lists are stored in a DataTable. I assume that I will have to switch between them during the iteration, but it is difficult for me to define a method for combining strings.

Thanks for any help.

- Brent

+4
source share
2 answers

I think something in this direction should do this 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 does not accept duplicates in any list and that function is passed to the larger list as a large list.

+1
source

If you want to join two standard lists and don't care about sorting, 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 keep some special order will be difficult. For example, suppose list2 does not contain red, what should be the first element: brown or red? Suppose list1 is yellow, but list2 is yellow second. What should be the order?

If you are trying to combine two data tables, there is a Merge method in the DataTable, which allows you to combine one DataTable into another.

DataTable.Merge

0
source

Source: https://habr.com/ru/post/1312391/


All Articles