user1285783
user1285783

Reputation: 59

How to select data for particular date in linq using C#

I am having List with data in the following format,

TF000040070004-29/08/12
TF000040070004-29/08/12
TF000040070005-29/08/12
TF000020010004-29/08/12
TF000020010007-29/08/12
TF000020010002-29/08/12
TF000010010012-29/08/12
TF000010010014-29/08/12
TF000010010014-29/08/12
TF000010010005-29/08/12
TF000010010005-29/08/12
TF000010010006-29/08/12
TF000010010002-29/08/12
TF000010010008-29/08/12
TF000010010008-29/08/12
TF000010010008-29/08/12
TF000010010008-29/08/12

I used the following linq query to get count, key value and min and max. Now I want to select the data for particular date.

var serialNumbers = from sn in code
                    group sn by sn.Substring(0, 10) into g
                    select new { Key = g.Key, 
                                 Cnt = g.Count(), 
                                 Min = g.Min(v => v.Substring(10)), 
                                 Max = g.Max(v => v.Substring(10)) };

Upvotes: 0

Views: 949

Answers (3)

rene
rene

Reputation: 42494

This will fail if there is no valid DateTime at the end of your string...

var selectionDate = new DateTime(2012,8,29);

var serialNumbers = from sn in code 
            where DateTime.Parse(
                         sn.Trim().Substring(sn.Trim().Length-8,8), 
                         new DateTimeFormatInfo {ShortDatePattern="dd/MM/yy"}) == 
                              selectionDate;
             group sn by sn.Substring(0, 10) into g 
             select new { Key = g.Key,  
                          Cnt = g.Count(),  
                          Min = g.Min(v => v.Substring(10)),  
                          Max = g.Max(v => v.Substring(10)) }; 

Upvotes: 0

RePierre
RePierre

Reputation: 9576

First of all you'll need to transform your data for better manipulation.

var transformed = code.Select(item=>
{
    var parts = item.Split(new string[]{"-"}, StringSplitOptions.None);
    var keyPart = parts[0].Substring(2);
    var key = long.Parse(keyPart);
    var date = DateTime.Parse(parts[1]);
    return new KeyValuePair<long, DateTime>(key, date);
}

After transformation, perform the queries you want on strongly-typed data:

var date = DateTime.Today; // your date here
var result = transformed.Where(item => item.Value == date);

Upvotes: 0

Spontifixus
Spontifixus

Reputation: 6660

Try the following:

from sn in rawData where sn.Substring(15, 8) == "29/08/12"
                   select sn;

You then can append your linq query (group by etc.) to that...

Upvotes: 1

Related Questions