Sort One Array from Another array order?

蓝咒 提交于 2020-01-14 16:32:49

问题


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.


回答1:


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);
}



回答2:


Well, let me rephrase your sorting requirements:

  1. 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
  2. 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 


来源:https://stackoverflow.com/questions/5158659/sort-one-array-from-another-array-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!