Dilshod
Dilshod

Reputation: 3331

Linq: Sorting the list based on another list

I have a list of strings List{"X", "W", "C", "A", "D", "B" } and I have another list of strings List{"A", "B", "C", "D"} that tells how the first list must be ordered. But the second list has only four items in it. I would like my first list to be ordered like this: A, B, C, D, X, W. Actually the last two letters X and W doesn't matter how they are ordered, but they should be at the end of the list.

I tried this:

var newList = list1.OrderBy(i=>list2.IndexOf(i));

but this gives me only four items.

Upvotes: 2

Views: 4709

Answers (3)

Hari Prasad
Hari Prasad

Reputation: 16966

One more way along with others.

List<string> list1 = new List<string>() {"X", "W", "C", "A", "D", "B" } ;
List<string> list2 = new List<string>() { "A", "B", "C", "D" } ;

var newList = list2.Intersect(list1)
                   .Union(list1.Except(list2));

Check Demo

Upvotes: 3

Jcl
Jcl

Reputation: 28272

This should work:

var newList = list1.OrderBy(i => { 
      var x = list2.IndexOf(i); 
      if(x == -1) 
        return int.MaxValue; 
      return x; });

Result (from LinqPad):

linqpad result

Upvotes: 2

Yacoub Massad
Yacoub Massad

Reputation: 27871

Your current code will give you 6 items. However, it will put X and W in the beginning since they have an index of -1 in list 2.

Here is how to fix that:

var list1 = new List<string> {"X", "W", "C", "A", "D", "B"};
var list2 = new List<string> {"A", "B", "C", "D"};

var newList = list1.OrderBy(x =>
{
    var index = list2.IndexOf(x);

    if (index == -1)
        index = Int32.MaxValue;

    return index;
})
.ToList();

Upvotes: 4

Related Questions