usr021986
usr021986

Reputation: 3511

Filter the Data According to range using linq

I have a datatable which contains following data as

SrNo Roll  Name
1    1     XYZ
99   45    ABC
150  120   POQ
10   9     RTY
190  180   MNZ

According to the range of of srNo the output should be derived & there should be a additional column Result should be added & according to the range the result should be filled with 0 or 1(if range is between 0-100 then result should be 0 if range is between 100-200 then result should be 1)

So the output will be

SrNo Roll  Name Result
1     1     XYZ  0
99    45    ABC  0
10    9     RTY  0

150   120   POQ   1

190  180   MNZ    1

I want to implement through linq

Please suggest any!!!

Thanks

Upvotes: 0

Views: 232

Answers (1)

tofutim
tofutim

Reputation: 23374

SrNo    Roll    Name    Result
1       1       XYZ     0
99      45      ABC     0
10      9       RTY     0
150     120     POQ     1
190     180     MNZ     1

Try this:

var dt = new DataTable();
dt.Columns.Add(new DataColumn("SrNo", typeof (int)));
dt.Columns.Add(new DataColumn("Roll", typeof (int)));
dt.Columns.Add(new DataColumn("Name", typeof (string)));

dt.Rows.Add(1, 1, "XYZ");
dt.Rows.Add(99, 45, "ABC");
dt.Rows.Add(150, 120, "POQ");
dt.Rows.Add(10, 9, "RTY");
dt.Rows.Add(190, 180, "MNZ");

var result = from r in dt.AsEnumerable()
             orderby (r.Field<int>("Roll") >= 100) ascending
             select new
                        {
                            SrNo = r.Field<int>("SrNo"),
                            Roll = r.Field<int>("Roll"),
                            Name = r.Field<string>("Name"),
                            Result = Convert.ToInt32(Math.Floor(r.Field<int>("Roll")/100.0))
                        };        

Console.WriteLine(
        "{0}\t{1}\t{2}\t{3}",
        "SrNo",
        "Roll",
        "Name",
        "Result");

foreach (var row in result)
{
    Console.WriteLine(
        "{0}\t{1}\t{2}\t{3}",
        row.SrNo,
        row.Roll,
        row.Name,
        row.Result);
}

Upvotes: 1

Related Questions