none
How to subtract elements with linq? RRS feed

  • Question

  • I want to change {10,15,17,27} to {5,2,10}.

    5=15-10

    2=17-15

    10=27-17

    How to do this using LINQ?


    • Edited by tangferry Wednesday, November 26, 2014 1:25 AM
    Wednesday, November 26, 2014 1:24 AM

Answers

  • Hello tangferry,

    Please have a try with below LINQ query:

    List<int> list = new List<int>() { 10, 15, 17, 27 };
    
    
                var result = (from e in list
    
                              let nextindex = list.IndexOf(e) + 1
    
                              let nextelement = list.ElementAt(nextindex == list.Count ? nextindex - 1 : nextindex)
    
                              select nextelement - e).ToList();
    
                result.RemoveAt(list.Count - 1);
    

    The result would be a collection which contains  {5,2,10}.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, November 27, 2014 1:16 AM
    Moderator