chinna g
chinna g

Reputation: 405

How to rearrange the one List same as another list?

I want to rearrange the list exactly same as another list.

List<string> list1= new List<string>();
            list1.Add("a");
            list1.Add("b");
            list1.Add("c");

List<string> list2= new List<string>();
            list2.Add("b");
            list2.Add("c");
            list2.Add("a");

Now i want to rearrange the list2 exaclty same as list1 , So after rearranging list2 , it should look like in the same order as list1

Upvotes: 0

Views: 131

Answers (3)

Theodor Zoulias
Theodor Zoulias

Reputation: 43474

For lists containing strings, and assuming that the two lists have the same elements in different order, and also assuming that the comparison of the elements is case sensitive, there is no need to keep the original elements. Strings have no hidden identity that needs to be preserved, other than their value. So here you are:

list1.Clear();
list1.AddRange(list2);

Upvotes: 0

smolchanovsky
smolchanovsky

Reputation: 1863

The IndexOf method has O(N) complexity. So, I propose this solution:

var list1 = new List<string> {"a", "b", "c"};
var list2 = new List<string> {"b", "c", "a"};

var list1Indexes = list1
    .Select((value, index) => (Index: index, Value: value))
    .ToDictionary(x => x.Value, x => x.Index);

list2 = list2
    .OrderBy(x => list1Indexes.TryGetValue(x, out var index) ? index : -1)
    .ToList();

Accessing an element of a dictionary by key is O(1) operation.

Upvotes: 2

fubo
fubo

Reputation: 45947

Linq approach

list2 = list2.OrderBy(list1.IndexOf).ToList();

If a item from list2 doesn't exist in list1, it will be placed first, because IndexOf returns -1 in that case.

Upvotes: 4

Related Questions