Sort One Array from Another array order?
var listOne = new string[] { "dog", "cat", "car", "apple"};
var listTwo = new string[] { "car", "apple"};
What I need is to order listOne by the order of items in listTwo (if present). So the new list would be in this order; "car", "apple", "dog", "cat"
I would like to do this in LINQ and have 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 evidently my Linq-Fu is weak. Any advise is appreciated.
You need all the items from listTwo that are in listOne followed by the remaining items from listOne?
var results = listTwo.Intersect(listOne).Union(listOne);
foreach (string r in results)
{
Console.WriteLine(r);
}
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
精彩评论