I have a list that contains a list of integers and another list that contains a class that holds both an integer and a string.
What I'm trying to do is sort my list alphabetically, putting the entries that exist in the first list first. Here is my code and expected output:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var myList = new List<int>();
myList.Add(5);
myList.Add(15);
var myclasses = new List<MyClass>();
myclasses.Add(new MyClass {MyId = 8, MyString = "Entry1"});
myclasses.Add(new MyClass {MyId = 12, MyString = "Entry2"});
myclasses.Add(new MyClass {MyId = 1, MyString = "Entry3"});
myclasses.Add(new MyClass {MyId = 15, MyString = "Entry4"});
myclasses.Add(new MyClass {MyId = 9, MyString = "Entry5"});
myclasses.Add(new MyClass {MyId = 5, MyString = "Entry6"});
foreach (MyClass c in myclasses.OrderBy(z => myList.Contains(z.MyId)).ThenBy(z => z.MyString )) {
Console.WriteLine("{0} ==> {1}", c.MyId, c.MyString);
}
// I'm expecting this output:
//
// 15 ==> Entry4
// 5 ==> Entry6
// 8 ==> Entry1
// 12 ==> Entry2
// 1 ==> Entry3
// 9 ==> Entry5
}
public class MyClass {
public int MyId { get; set; }
public string MyString { get; set; }
}
}
As you can see from my expected output, I want Entry6
and Entry4
to appear first since they appear in the first list. Then I just want an alphabetical list. I thought my LINQ statement would be correct, but its not giving me the correct results. Any help would be appreciated.