C# Not able to construct line inside LINQ Select statement

T.Zacks 3,986 Reputation points
2022-02-04T14:06:28.043+00:00

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;
            dtMain.Rows.Add(dr);

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

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

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

                if(Salary>2500)
                {
                    empname.Add(Name);
                },

            });

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.

thanks

C#
C#
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,651 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,496 Reputation points
    2022-02-04T14:20:22.563+00:00

    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