Sorting one array from another array?

var listOne = new string[] { "dog", "cat", "car", "apple"};
var listTwo = new string[] { "car", "apple"};

I need to order listOne in the order of the items in listTwo (if any). So the new list will be in that order; "car", "apple", "dog", "cat"

I would like to do this in LINQ and tried this:

var newList = from l1 in listOne
              join l2 in listTwo on l1 equals l2 in temp
              from nl temp.DefaultIfEmpty()
              select nl;

But it returns null, so obviously my Linq-Fu is weak. Any recommendations are appreciated.

+3
source share
2 answers

Do you need all listTwo elements that are in listOne and then the rest of the elements from listOne?

var results = listTwo.Intersect(listOne).Union(listOne);
foreach (string r in results)
{
    Console.WriteLine(r);
}
+4
source

Ok, let me rephrase your sorting requirements:

  • , , , , : ,
  • , , ,

:

void Main()
{
    var listOne = new string[] { "dog", "cat", "car", "apple"};
    var listTwo = new string[] { "car", "apple"};

    var elements1 =
        from element in listTwo
        where listOne.Contains(element)
        select element;
    var elements2 =
        from element in listOne
        where !listTwo.Contains(element)
        select element;

    elements1.Concat(elements2).Dump();
}

LINQ, :

void Main()
{
    var listOne = new string[] { "dog", "cat", "car", "apple"};
    var listTwo = new string[] { "car", "apple"};

    var elements = listTwo.Where(e => listOne.Contains(e))
        .Concat(listOne.Where(e => !listTwo.Contains(e)));

    elements.Dump();
}

( LINQPad):

car 
apple 
dog 
cat 
+3

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


All Articles