我在数组中有以下键值对,并尝试将它们提取并加载到集合中。
以下代码正常运行,但可以使用linq优化:
string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true";
List<WebSiteAddress> _websiteList = new List<WebSiteAddress>() ;
WebSiteAddress _website = new WebSiteAddress();
string[] _websiteData = _divider[1].Split('=');
string[] _WebsiteKeyValuePair = _websiteData[1].Split(',');
for (int j = 0; j < _WebsiteKeyValuePair.Length; j++)
{
string key = _WebsiteKeyValuePair[j].Split(':')[0];
string value = _WebsiteKeyValuePair[j].Split(':')[1];
if (key.ToLower() == "url")
{
_initWebsite.Url = value;
}
else if (key.ToLower() == "isdefault")
{
_website.IsDefault = Convert.ToBoolean(value);
_websiteList.Add(_website);
}
}
答案 0 :(得分:3)
您可以执行以下操作:
string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true";
List<WebSiteAddress> _websiteList = _data
.Split(new string[]{"url:"}, StringSplitOptions.RemoveEmptyEntries)
.Select(site => site.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries))
.Where(site => site.Length > 1)
.Select(site => new WebSiteAddress { Url = site[0], IsDefault = site[1].ToLower().Replace("isdefault:", "") == "true"})
.ToList();