Intruder Intruder - 2 months ago 19
C# Question

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.

Answer

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();
Comments