Pasting the working version of code, try it on visual studio or Linqpad, Main question post code in the end
void Main()
{
PGSSnapshotDataContract pgs = new PGSSnapshotDataContract();
ProductMovementActivityOutputData ob1 = new ProductMovementActivityOutputData(new DateTime(2016, 08, 10, 06, 57, 20), DateTime.Now, "17M00816A", "1155581", "InProgress");
ProductMovementActivityOutputData ob3 = new ProductMovementActivityOutputData(DateTime.Now, DateTime.Now, "17M00805B", "1158479", "InProgress");
ProductMovementActivityOutputData ob2 = new ProductMovementActivityOutputData(new DateTime(2016, 08, 10, 04, 40, 50), new DateTime(2016, 08, 10, 09, 57, 20), "M2", "1155581", "InProgress");
ProductMovementActivityOutputData ob4 = new ProductMovementActivityOutputData(new DateTime(2016, 08, 10, 07, 00, 00), new DateTime(2016, 08, 10, 09, 00, 00), "M2", "1158479", "InProgress");
ProductMovementActivityOutputData ob5 = new ProductMovementActivityOutputData(new DateTime(2016, 08, 10, 09, 10, 00), new DateTime(2016, 08, 10, 09, 20, 00), "M2", "1158479", "InProgress");
ProductMovementActivityOutputData ob6 = new ProductMovementActivityOutputData(new DateTime(2016, 08, 11, 07, 00, 00), new DateTime(2016, 08, 11, 09, 00, 00), "M2", "1158479", "InProgress");
pgs.ProductMovements.Add(ob1);
pgs.ProductMovements.Add(ob2);
pgs.ProductMovements.Add(ob3);
pgs.ProductMovements.Add(ob4);
pgs.ProductMovements.Add(ob5);
pgs.ProductMovements.Add(ob6);
var productMovementsList = pgs.ProductMovements.OrderBy(b => b.StartTime).GroupBy(x => x.SourceCode) ;
// foreach (var v in productMovementsList)
// Console.WriteLine(v);
var list = productMovementsList.SelectMany(x => x.Zip(x.Skip(1), (a, b) => (a.EndTime > b.StartTime) ? a.SourceCode : null).Where(y => y != null));
foreach (var l in list)
Console.WriteLine(l);
}
public class ProductMovementActivityOutputData
{
public ProductMovementActivityOutputData(DateTime start, DateTime end, String src, String dest, String stat)
{
StartTime = start;
EndTime = end;
SourceCode = src;
DestinationCode = dest;
Status = stat;
}
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string SourceCode { get; set; }
public string DestinationCode { get; set; }
public string Status { get; set; }
}
public class PGSSnapshotDataContract
{
public PGSSnapshotDataContract()
{
this.ProductMovements = new List<ProductMovementActivityOutputData>();
}
public List<ProductMovementActivityOutputData> ProductMovements { get; set; }
}
Question:
Want to optimize this piece of code in the Main function:
var list = productMovementsList.SelectMany(x => x.Zip(x.Skip(1), (a, b) =>
(a.EndTime > b.StartTime) ? a.SourceCode : null).Where(y => y != null));
Here first I deliberately add value SourceCode or null, which is just to be filtered out in the end using Where, is there a better mechanism
