Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
List<int> dd = new List<int>() { 1, 2, 3, 4, -1, -2, -4, 5, 9, 7, 5, 8, 9 };


how to Divide list in lambda with The condition is positive or negative number



result =[1,2,3,4],[-1,-2,-4],[5,9,7],[7, 5, 8, 9]


What I have tried:

<pre>   List<int> dd = new List<int>() { 1, 2, 3, 4, -1, -2, -4, 5, 9, 7, 5, 8, 9 };


how to Divide list in lambda with The condition is positive or negative number



result =[1,2,3,4],[-1,-2,-4],[5,9,7],[7, 5, 8, 9]
Posted
Updated 9-Jan-21 4:22am
Comments
[no name] 9-Jan-21 10:00am    
How did you manage to turn one 7 into two 7's? [...7] and [7...]

And you want the result to be a "List of lists"?
BillWoodruff 9-Jan-21 12:17pm    
You have not shown any code you TRIED: you just show the result you want.
Sandeep Mewara 9-Jan-21 15:33pm    
Though you have tagged C#, can you confirm its in c# or python that you are trying it?

1 solution

You can't really use Linq for that because Linq is not defined as a sequential execution stream - it could be out of order and you'd get well confused. It normally is executed from the start of the sequence to the end, but that isn't set in stone - a multithreaded optimisation could put it out of order and your sequences would be broken.

Instead, use simple, obvious code:
C#
List<int> dd = new List<int>() { 1, 2, 3, 4, -1, -2, -4, 5, 9, 7, 5, 8, 9 };
bool positive = dd[0] >= 0;
List<List<int>> results = new List<List<int>>();
List<int> current = new List<int>();
results.Add(current);
foreach (int i in dd)
    {
    if (positive && i >= 0) current.Add(i);
    else if (!positive && i < 0) current.Add(i);
    else
        {
        positive = !positive;
        current = new List<int>();
        results.Add(current);
        current.Add(i);
        }
    }
If you want to break a sequence when a sequence stops increasing / decreasing (and your sample data implies that but doesn't confirm it) then it's fairly obvious how to add that in.
 
Share this answer
 
Comments
BillWoodruff 9-Jan-21 12:22pm    
I have a suspicion there's some weirdness you could do using 'groupby ... but, i am not going there :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900