Intruder
Intruder

Reputation: 145

Using Let in Lambda Expression while querying from a datatable

I have a data table and I need to convert the contents of that data table to a class List and I used Linq for that.It worked well.But I was asked to convert that linq query to Lambda Expression and there I had a Little trouble while using Let.I will the sample code.

Working linq query:

var NewUser = (from dt in dsMappedDataFields.Tables[0].Rows.Cast<DataRow>()
               let tempDetails = dt.Field<string>("Name") == "Rojer" ? "NW" : "India"
               let tempNumber = tempDetails == "India" ? "918956" : "0456"
               select new User
                        {
                           Name = dt.Field<string>("Name"),
                           Age = dt.Field<int>("Age"),
                           Details = tempDetails,
                           Number = tempNumber
                        }).ToList();

Lambda expression:

var User = dsMappedDataFields.Tables[0].Rows.Cast<DataRow>().

                             Select(dr =>
                                 new User
                                 {
                                     Name = dr.Field<string>("Name"),
                                     Age = dr.Field<int>("Age"),
                                     Details = dr.Field<string>("Details"),
                                     Number = dr.Field<string>("Number")
                                 }).ToList();

As you can see I have to check some conditions before converting the data to list which I have done earlier.. Please do help me with solving this issue.

Upvotes: 1

Views: 1172

Answers (2)

poke
poke

Reputation: 387587

The lambda you pass to Select can have a block, so you can add any kind of code there:

var User = dsMappedDataFields.Tables[0].Rows
    .Cast<DataRow>()
    .Select(dr =>
    {
        var tempDetails = dt.Field<string>("Name") == "Rojer" ? "NW" : "India";
        var tempNumber = tempDetails == "India" ? "918956" : "0456";
        return new User
        {
            Name = dr.Field<string>("Name"),
            Age = dr.Field<int>("Age"),
            Details = tempDetails,
            Number = tempNumber,
        };
    })
    .ToList();

Upvotes: 4

We can use lambda expression in this case :

var User = dsMappedDataFields.Tables[0].Rows.Cast <DataRow>().
Select(dr = > new User {
    Name = dr.Field<string>("Name"),
    Age = dr.Field<int>("Age"),
    Details = dr.Field<string>("Name") == "Rojer" ? "NW" : "India",
    Number = dr.Field<string>("Name") == "Rojer" ? 0456 : 918956,
}).ToList();    

I tried the sample it works as you need.

Thanks, Narasimha

Upvotes: -1

Related Questions