Well, let me rephrase your sorting requirements:
- First, all the items from the first list, that is also present in the second list, and return them in the order they appear in that second list, or: all the elements from the second list, if they appear in the first list
- Then, all the items from the first list, that is not in that second list, and return them in the order they appear in that first list
This code would do the trick:
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();
}
You can also rewrite it without the LINQ syntax to make it a bit shorter:
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();
}
Output (through LINQPad):
car
apple
dog
cat
listOne? If so, should they be preserved?