poorna
poorna

Reputation: 73

Convert foreach to linq

Can anyone tell me how do i convert the below code to linq.I am trying to get the endpoint address from web.config file using contract name.

I need to convert below for each loop to linq .

string csEndPoint =null;
ClientSection clientSettings = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
   foreach (ChannelEndpointElement endpoint in clientSettings.Endpoints) {
                    if (endpoint.Contract == "CsWebService.ICsWebService") {
                        ccEndPoint = endpoint.Address.ToString();
                        break;
                    }
                }

Upvotes: 0

Views: 1026

Answers (2)

fubo
fubo

Reputation: 46005

Linq approach with FirstOrDefault

string csEndPoint = clientSection.Endpoints.Cast<ChannelEndpointElement>().FirstOrDefault(e => e.Contract == "CsWebService.ICsWebService")?.Address.ToString();

.NET 4.5 and below

string csEndPoint = clientSection.Endpoints.Cast<ChannelEndpointElement>()
                                 .Where(e => e.Contract == "CsWebService.ICsWebService")
                                 .Select(x => x.Address.ToString()).FirstOrDefault();

Upvotes: 5

arun thatham
arun thatham

Reputation: 500

Try this

string csEndPoint = (from k in clientSettings.Endpoints
         where k.Contract == "CsWebService.ICsWebService"
         select k.Address.ToString()).FirstOrDefault();

Upvotes: 1

Related Questions