1

I'm not very familiar with LinQ and i have a small(i think) problem. Basically i' deserializing an xml file to the array of following items:

public string stringId{ get; set; }
public string sgent { get; set; }
public string status{ get; set; }
public string recallDate { get; set; }
public string product{ get; set; }
public string sendMethod{ get; set; }
public string campaign{ get; set; }
public string comment{ get; set; }
public string sgentId{ get; set; }
public string dateOfSell { get; set; }

My list so far looks like this

var model = from r in selling.sales
            where r.sgentId == idFromLoginAction.ToString()
            orderby r.dateOfSell
            select r;

It works but What I want to achieve is to get list of this items groupped by dateOfSell property so later on i can show this in the view in the way where Date property will be shown only once for every same date and below this date i want to show the list of all other properties where dateOfSell property was this speciffic date.

I'm pretty sure i Can achieve this groupping with LinQ. Am I right ? Is it possible, or it's a bad approach ? Bellow i've wrote a little sketch to show what is my point:

2014-01-08
Prop 1    Prop2    Prop3    prop4 ... etc
Prop 1    Prop2    Prop3    Prop4 ... etc
2014-01-07
Prop 1    Prop2    Prop3    prop4 ... etc
Prop 1    Prop2    Prop3    Prop4 ... etc
ETC ...
leppie
  • 115,091
  • 17
  • 196
  • 297
MajkeloDev
  • 1,661
  • 13
  • 30
  • 1
    possible duplicate of [Group by in LINQ](http://stackoverflow.com/questions/7325278/group-by-in-linq) – devqon Jan 08 '15 at 14:40

2 Answers2

1

use GroupBy this way, do like this before Select :

var model = from r in selling.sales 
            where r.sgentId == idFromLoginAction.ToString() 
            orderby r.dateOfSell
            group r by r.dateOfSell into g
            select new { DateOfSell = g.Key, Sales = g.ToList() };
Magnus
  • 45,362
  • 8
  • 80
  • 118
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0
var result = selling.sales.GroupBy(s => s.dateOfSell, (key, g) => new { SellDate = key, OtherValues = g.ToList() });

Then you can do:

        foreach(var item in result){
// Your key you grouped By
    var selDate = item.SellDate;

// List of Other Items
    var groupedItems = item.OtherValues;


        }

Look at the link mentioned by @Devqon: Group by in LINQ

Community
  • 1
  • 1
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119