jeudi 29 juillet 2021

Find inconsistent and consecutive objects from List in C#

I'm having trouble with getting a consecutive and nonconsecutive number from list. I'm sure it's pretty simple, but i can't get it.

If consecutiveNum=2, then if result from before last and last is equal, i need to throw an exception.

If nonConsecutiveNum=4, then if from 10 pieces there are 4 with same result, i need to throw an exception.

I'm trying with nested loops and couple checks, but i didn't succeeded at all. Same is for both cases, i tried a couple solutions with System.LINQ, but again i don't get the result i need.

Thanks in advance to all of you!

int consecutiveNum = 2;
int nonConsecutiveNum = 4;
int counter = 1;

var sensInfo = new ResultInfo()
                {
                    Product = CurrentLot.Info.Product,
                    Result = code
                };

 if (consecutiveNum > 0)
                    {
                        for (int i = ListSensors.Count + 1; i >= 0; i--)
                        { 
                            if (sensInfo.Result == ListSensors[i].Result)
                            {
                                counter++;
                                if (counter >= consecutiveNum)
                                {
                                    throw new Exception("Consecutive num");
                                }
                            }
                        }
                    }

if (nonConsecutiveNum > 0)
                    {
                        for (int i = 0; i < ListSensors.Count; i++)
                        {
                            for (int j = i + 2; j < ListSensors.Count - 2; j++)
                            {
                                if (ListSensors[i].Result == ListSensors[i+1].Result)
                                    continue;
                                if (ListSensors[i].Result == ListSensors[j].Result)
                                {
                                    counter++;
                                    if (counter >= nonConsecutiveNum)
                                    {
                                        throw new Exception("NonConsecutive num");
                                    }
                                }
                            }
                        }
                    }

Aucun commentaire:

Enregistrer un commentaire