任何人都可以告诉我如何将以下代码转换为linq。我正在尝试使用合同名称从web.config文件获取端点地址。
我需要将每个循环转换为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;
}
}
答案 0 :(得分:5)
Linq
使用FirstOrDefault
string csEndPoint = clientSection.Endpoints.Cast<ChannelEndpointElement>().FirstOrDefault(e => e.Contract == "CsWebService.ICsWebService")?.Address.ToString();
.NET 4.5及以下
string csEndPoint = clientSection.Endpoints.Cast<ChannelEndpointElement>()
.Where(e => e.Contract == "CsWebService.ICsWebService")
.Select(x => x.Address.ToString()).FirstOrDefault();
答案 1 :(得分:1)
试试这个
string csEndPoint = (from k in clientSettings.Endpoints
where k.Contract == "CsWebService.ICsWebService"
select k.Address.ToString()).FirstOrDefault();