tags:

views:

108

answers:

1

I have a master list of colors:

List<string> completeList = new List<string>{"red", "blue", "green", "purple"};

I'm passing in a List of existing colors of a product

List<string> actualColors = new List<string>{"blue", "red", "green"};

How do I get a list back that is in the order of the completeList? (red,blue,green)

+16  A: 
var ordered = completeList.Intersect(actualColors);

If that doesn't work, do this

var ordered = actualColors.Intersect(completeList);
Daniel A. White
Linq also has `Union` too and a bunch of awesome features.
Daniel A. White
Neat! I had no idea it could be done that simply.
mezoid
For simplicity +1
Shankar Ramachandran
I'm not sure Intersect() guarantees stable ordering according to the left sequence. The implementation probably uses a hash join which means it might honor the sequence of one of the operands, but I'm not sure it's specifically the left. For all you know, it could be actualColors.Intersect(completeList) which yields an equivalent (sans ordering) sequence.
Avish
@Avish. According to msdn it is:"When the object returned by this method is enumerated, Intersect enumerates first, collecting all distinct elements of that sequence. It then enumerates second, marking those elements that occur in both sequences. Finally, the marked elements are yielded in the order in which they were collected."http://msdn.microsoft.com/en-us/library/bb460136.aspx
Daniel A. White