Search code examples
c#linqobservablecollectionskip-take

Loop through observable collection to create a new observable collection


Hi everyone I have an observable collection and what I want is to create a new observable collection that will take the first 6 objects of the original one and skip the next 12 but on a loop so take 6 skip 12 take 6 skip 12 as long as there are objects in there.

I have read about the take and skip methods and have used them but to little effect. If I say take 6 it will take the first 6 and then stop without looping if I do the take 6, skip 12 it will never even go into the loop just skip it and so on and so forth. Hope u guys can help here is some code.

 private void UcitajReport()
    {
        _report = new ObservableCollection<ReportClass>();


        foreach (Brojevi b in SviBrojevi.Skip(0).Take(6))


        {


            ReportClass r = new ReportClass();

            r.RpBrId = b.ID;
            r.RpBrBroj = b.Broj;
            r.RpBrKolo = b.Kolo;

            r.RpKlKolo = (from ko in Kola
                        where ko.ID == b.KoloId
                        select ko.Naziv).First();


            r.RpKlGodina = (from ko in Kola
                            where ko.ID == b.KoloId
                            select ko.Godina).First();


            r.RpKlDatum = (from ko in Kola
                           where ko.ID == b.KoloId
                           select ko.Datum).First();


            r.RpBjBoja = (from ko in Kola
                          where ko.ID == b.KoloId
                          select ko.Boja).First();


            r.RpDobIznos = (from d in Dobici
                            where d.Kolo == b.Kolo
                            select d.Iznos).First();


            _report.Add(r);


        }

    }

Solution

  • Personally, I would just keep track of the foreach iterator as an integer and do some checks within the loop to determine whether you are interested in the current item or not, by comparing the iterator value with a "skip" value and a "keep" value.

    class Program
    {
        static void Main(string[] args)
        {
            var populatedList = new List<String>
            {
                "One", "Two", "Three", "Four", "Five",
                "Six", "Seven", "Eight", "Nine", "Ten"
            };
    
            var fillThisList = new List<String>();
    
            int itr = 1;
            int keep = 3;
            int skip = 7;
            foreach (var item in populatedList)
            {
                if (itr == skip)
                {
                    // reset the iterator
                    itr = 1;
                    continue;
                }
                if (itr <= keep)
                {
                    fillThisList.Add(item);
                }
                itr++;
            }
        }
    }
    

    fillThisList will then be populated with "One", "Two", "Three", "Eight", "Nine", "Ten".