1

I have a LINQ query as below,

 var sortedResults = (from r in this.CurrentTemplateInfos
                      where r.EffectiveEnd == null
                      orderby r.Description
                      select r); 

From the above query ,field Description is made of 3 sub strings(Showtype:Show:StartDate-Endate) separated by Colon (:). Now as per the new requirement i need to do orderby ascending for first two fields(Showtype:Show) and descending by StartDate from the description value, e.g.

Show : Main Street Trolley : 6/12/2010 - 7/15/2010

ShowType : Parades : 2/10/2010 - 6/16/2010

ShowType : Parades : 6/17/2010 - 8/26/2010

ShowType : Parades : 8/27/2010 - 10/26/2010

Output should be

Show : Main Street Trolley : 6/12/2010 - 7/15/2010

ShowType :Parades : 8/27/2010 - 10/26/2010

ShowType : Parades : 6/17/2010 - 8/26/2010

ShowType : Parades : 2/10/2010 - 6/16/2010

please help me on this.

Konamiman
  • 49,681
  • 17
  • 108
  • 138
anitha lm
  • 61
  • 5

2 Answers2

2

Break the field up into separate fields with a helper type, and then use that in order by clauses. Something like:

// Elsewhere
class SortFields {
  public string Field1 { get; set; }
  public string Field2 { get; set; }
  public DateTime StartDate { get; set; }

  public static SortFields SplitInput(string input) {
    // Factory... Implement split/parse logic
  }
}

and then

from r in this.CurrentTemplateInfos
where r.EffectiveEnd == null
let fields = SortField.SplitInput(r.Description)
// This means sort by Field1, then Field2 and then StartDate
// and the default in each criterion is ascending unless you
// specify descending keyword.
orderby fields.Field1, fields.Field2, fields.StartDate descending 
select r

Note, one could use use multiple let clauses to do the split/parse, but I think the little helper type is clearer.

Richard
  • 106,783
  • 21
  • 203
  • 265
1
var sortedResults = from r in this.CurrentTemplateInfos
                    where r.EffectiveEnd == null
                    let parts = r.Description.Split(':')
                    let firstPart = parts[0] + parts[1]
                    let startDate = DateTime.Parse(parts[2].Split('-').First().Trim())
                    orderby firstPart, startDate descending
                    select r;
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92