Here I'm merging a list to end of another list after sorting it according to another list.This should sort processdetails list according to the order in routeplans list if any item not present in processdetails list is found it should keep the order and add it to processdetails list. Simply saying it just merging two lists based on another list.The below code works fine, I want to know whether there is cleaner way of doing this.if possible in linq.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortByList
{
public class OnGoingProcess
{
public long Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
}
class Program
{
static void Main(string[] args)
{
var processDetails = new List<OnGoingProcess>();
processDetails.Add(new OnGoingProcess() { Id = 120, Name = "Process 29", Code = "T20" });
processDetails.Add(new OnGoingProcess() { Id = 100, Name = "Process 2", Code = "A20" });
processDetails.Add(new OnGoingProcess() { Id = 99, Name = "Process 3", Code = "S20" });
processDetails.Add(new OnGoingProcess() { Id = 85, Name = "Process 229", Code = "B20" });
processDetails.Add(new OnGoingProcess() { Id = 220, Name = "Process 39", Code = "C20" });
processDetails.Add(new OnGoingProcess() { Id = 15, Name = "Process 20", Code = "D20" });
processDetails.Add(new OnGoingProcess() { Id = 101, Name = "Process 129", Code = "G20" });
var routePlans = new List<OnGoingProcess>();
routePlans.Add(new OnGoingProcess() { Id = 100, Name = "Process 2" });
routePlans.Add(new OnGoingProcess() { Id = 120, Name = "Process 29" });
routePlans.Add(new OnGoingProcess() { Id = 222, Name = "Process new" });
routePlans.Add(new OnGoingProcess() { Id = 85, Name = "Process 229" });
routePlans.Add(new OnGoingProcess() { Id = 101, Name = "Process 129" });
var sortedPlans = new List<OnGoingProcess>();
foreach (var plan in routePlans)
{
var selectedDetails = processDetails.Where(x => x.Id == plan.Id).ToList();
if (selectedDetails.Any())
{
sortedPlans.AddRange(selectedDetails);
processDetails.RemoveAll(x => x.Id == plan.Id);
}
else
{
sortedPlans.Add(plan);
}
}
processDetails.AddRange(sortedPlans);
foreach (var sorted in processDetails)
{
Console.WriteLine("Id : " + sorted.Id + " Name : " + sorted.Name + " Code : " + sorted.Code );
}
Console.ReadKey();
//Id : 99 Name : Process 3 Code : S20
//Id : 220 Name : Process 39 Code : C20
//Id : 15 Name : Process 20 Code : D20
//Id : 100 Name : Process 2 Code : A20
//Id : 120 Name : Process 29 Code : T20
//Id : 222 Name : Process new Code :
//Id : 85 Name : Process 229 Code : B20
//Id : 101 Name : Process 129 Code : G20
}
}
}