C# Not able to construct line inside LINQ Select statement

T.Zacks 3,981 Reputation points

see the code

            string Name = "";
            int ID = 0;
            Decimal Salary = 0;
            DataRow dr = null;
            DataTable dtMain = new DataTable();
            dtMain.Columns.Add("ID", typeof(int));
            dtMain.Columns.Add("Name", typeof(string));
            dtMain.Columns.Add("Salary", typeof(decimal));

            dr = dtMain.NewRow();
            dr["ID"] = 1;
            dr["Name"] = "Mathew";
            dr["Salary"] = 2500;

            dr = dtMain.NewRow();
            dr["ID"] = 2;
            dr["Name"] = "John";
            dr["Salary"] = 1570;

            dr = dtMain.NewRow();
            dr["ID"] = 3;
            dr["Name"] = "Kathy";
            dr["Salary"] = 3200;

            List<string> empname=new List<string>();
            dtMain.AsEnumerable().Select(a =>
                Name = a.Field<string>("Name"),
                Salary = a.Field<decimal>("Salary"),



i am not able to add or construct line with in LINQ select. how to achieve it ? please guide me with sample code as a result i can write multi line if else with in LINQ select statement. please show me the way.


An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,168 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,401 Reputation points

    Do you mean something like this?:

    List<string> empname = dtMain.AsEnumerable()
        .Where(a => a.Field<decimal>("Salary") > 2500)
        .Select(a => new {
            ID = a.Field<int>("ID"),
            Name = a.Field<string>("Name"),
            Salary = a.Field<decimal>("Salary")

    A .Select() shouldn't have side-effects, i.e. it shouldn't be editing the state of your program from inside the function you pass it. It should just map from one value to another and that's it.

    In the snippet above the if statement is moved out of the mapping function and into a .Where() which configures a predicate/filter, which will be use to exclude items that don't satisfy the condition (i.e. if the Salary isn't 2500+)

    0 comments No comments

0 additional answers

Sort by: Most helpful