Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of strings by another list of strings [duplicate]

Tags:

c#

sorting

linq

I have a list of strings that I want to sort by another list of strings and if there are items in the list that is not in the comparer list I want them as they are at the end of the list. How can I do this?

So if I have this list: List<string> {"A","T","G","F","V","E","W","Q" }
and I have a comparer: List<string> {"T","F","V","A" }
I want the result to be: List<string> {"T","F","V","A","G","E","W","Q" }

Thanks!

like image 853
Johan Ketels Avatar asked Feb 26 '15 13:02

Johan Ketels


1 Answers

It looks like you need to use Intersect and Except like:

List<string> originalList = new List<string> {"A", "T", "G", "F", "V", "E", "W", "Q"};
List<string> compareList = new List<string> {"T", "F", "V", "A"};

var intersectedItems = compareList.Intersect(originalList);
var notIntersectedItems = originalList.Except(compareList);
var resultList = intersectedItems.Concat(notIntersectedItems).ToList();

You will get:

resultList = T,F,V,A,G,E,W,Q
like image 118
Habib Avatar answered Sep 23 '22 20:09

Habib