TNO TNO - 28 days ago 4
C# Question

List Occurence wise read c#

I have Class Like this

public class RoomDetails
{
public int RoomIndexID {get;set;} --(This is No of Rooms)
public int roomcategoryID {get;set;} -- (This is No of Category that room have)
public decimal roomPrice{get;set;}
public string roomCategory{get;set;}
}


So i have RoomDetails List like this(data)


  • 1,1,200,Single Bed

  • 2,1,250,Double Bed

  • 2,2,400,Double Bed with Extra View

  • 2,4,530,Tripple Bed

  • 3,1,530,Tripple Bed

  • 3,2,600,Triple Large Bed



so i want to read this list following procedure.


  • 1,1,200,Single Bed

  • 2,1,250,Double Bed

  • 3,1,530,Tripple Bed







  • 1,1,200,Single Bed

  • 2,1,250,Double Bed

  • 3,2,600,Triple Large Bed







  • 1,1,200,Single Bed

  • 2,2,400,Double Bed with Extra View

  • 3,1,530,Tripple Bed







  • 1,1,200,Single Bed

  • 2,2,400,Double Bed with Extra View

  • 3,2,600,Triple Large Bed







  • 1,1,200,Single Bed

  • 2,4,530,Tripple Bed

  • 3,1,530,Tripple Bed







  • 1,1,200,Single Bed

  • 2,4,530,Tripple Bed

  • 3,2,600,Triple Large Bed



please ask if you have any problem regrading my question.

This is example

my data list is like this


  • Room A -- A1

  • Room B -- B1 , B2 , B3

  • Room C -- C1 , C2



(Actually A ,B, C means RoomIndexID 's and A1,B1,B2,B3,C1,C2 is roomcategoryID 's)
so I want to read it like this.


  • A1,B1,C1

  • A1,B1,C2

  • A1,B2,C1

  • A1,B2,C2

  • A1,B3,C1

  • A1,B3,C2


Answer

If you want "LINQy" solution, it will be a little complicated. Please note that it is LINQ to object, so you will need to call .ToList() first if you have IQueryable (for example from EntityFramework).

var total = list.GroupBy(x=>x.RoomIndexID)
    .Select(x=>x.Count())
    .Aggregate(1, (s,d)=>s*d);

var counts = list.GroupBy(x => x.RoomIndexID)
    .ToDictionary(x => x.Key, x => x.Count());

var nums = list.GroupBy(x => x.RoomIndexID)
    .Select(x => x.Select((p, i) => new {i, p}))
    .SelectMany(x => x)
    .ToList();

var result = Enumerable.Range(0, total)
    .Select(x =>
        nums.Where(y => {               
            var c = counts[y.p.RoomIndexID];
            var p = counts
                      .Where(z => z.Key > y.p.RoomIndexID)
                      .Aggregate(1, (s,d)=>s*d.Value);

            return y.i == x/p%c;
        })
        .Select(y => y.p)
    );

Demo here: https://dotnetfiddle.net/udf6VA

Comments