0

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;
                    }
                }
3
  • 1
    I'm sure you tried something. Where/how did it fail? Commented Jun 14, 2017 at 7:49
  • I tried this string csEndPoint = clientSettings.Endpoints.FirstOrDefault(e => e.Contract == "CsWebService.ICsWebService")?.Address.ToString(); but FirstOrDefault showing error ChannelEndpointElement doenot contain a defination for first or default
    – poorna
    Commented Jun 14, 2017 at 7:57
  • Next time when you ask a question, please show what you tried and include any info on errors and failures. It was impossible to guess that clientSettings.Endpoints only implemented IEnumerable, not IEnumerable<T>. Commented Jun 14, 2017 at 9:33

2 Answers 2

5

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();
0
1

Try this

string csEndPoint = (from k in clientSettings.Endpoints
         where k.Contract == "CsWebService.ICsWebService"
         select k.Address.ToString()).FirstOrDefault();
3
  • if this is not working then the foreach you have mentioned should also not work. Commented Jun 14, 2017 at 8:46
  • 1
    @arunthatham foreach is working because of the explicit ChannelEndpointElement loop variable (instead of usual var). If you do (from ChannelEndpointElement k in ..., the query will work as well.
    – Ivan Stoev
    Commented Jun 14, 2017 at 9:45
  • Thanks Ivan. Another thing that comes to my mind is to use a let keyword within the query and type casting the variable with ChannelEndpointElement Commented Jun 14, 2017 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.