Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select case in linq in C#

Tags:

c#

linq

How can I trasfrom the following sql statement into linq

 select  AdsProperties.AdsProID,
         AdsProperties.IsActive,
         AdsProperties.Name,
           case
                when AdsProperties.ControlType =1 then -- TextBox
                  'Textbox'
                when AdsProperties.ControlType =2 then -- DropDown
                  'Dropdown'
                when AdsProperties.ControlType =3 then -- ConboBox
                  'ComboBox'
                else -- RadioButton
                  'RadioButtont'
           end as ControlType   
   from CLF.utblCLFAdsPropertiesMaster as AdsProperties

I have tried this

var query = from AdsProperties in db.utblCLFAdsPropertiesMasters
            select new
            {
                AdsProperties.AdsProID,
                AdsProperties.Name,
                AdsProperties.IsActive,
                ControlType = AdsProperties.ControlType == 1 ? (int?)"TextBox" : null,
                ControlType = AdsProperties.ControlType == 2 ? (int?)"Dropdown" : null,
                ControlType = AdsProperties.ControlType == 3 ? (int?)"ComboBox" : null,                 
                ControlType = AdsProperties.ControlType == 4 ? (int?)"RadioButton" : null)
            };
            dt = query.CopyToDataTableExt();

but I am getting this error

`an anynomous type cannot have multiple properties with the same name`

I know that it may be easy and simple. However, being new in linq, I haven't the approrpiate experience to deal with it. Any help would be appreciated. Thanks in advance.

like image 657
Arunesh Avatar asked Feb 25 '14 10:02

Arunesh


People also ask

What is select in Linq?

Select() takes each source element, transforms it, and returns a sequence of the transformed values.

Is Linq thread safe?

They're not thread safe.


1 Answers

Declare an array of strings as:

string[] controls = new string[] {"TextBox","Dropdown","ComboBox","RadioButton"};

Modify your query as mentioned below:

var query = from AdsProperties in db.utblCLFAdsPropertiesMasters
                    select new
                    {
                        AdsProperties.AdsProID,
                        AdsProperties.Name,
                        AdsProperties.IsActive,
                        ControlType = AdsProperties.ControlType < controls.Length ? controls[AdsProperties.ControlType-1] : null
                    };
        dt = query.CopyToDataTableExt();
like image 94
M.S. Avatar answered Oct 14 '22 12:10

M.S.