我在C# and .net 3.5
中有以下代码正常工作,但需要知道这是否可以简化,可能是使用Linq还是其他?基本上我正在读取一个xml文件来获取列名。如果“列的isactive属性为”true“,则尝试复制字典对象中的列和sequence属性。我在代码的其他部分使用此字典对象。我遍历元素然后属性并查找列它是活动的,如果是活动的,我存储序列,最后将列和序列添加到字典中。
var doc = XDocument.Load("DataStructure.xml");
var cols = doc.XPathSelectElements("/datastructure/" + sPageName + "/columns");
Dictionary<string, int> columns = new Dictionary<string, int>();
bool bAddData = true;
int sSequence = 0;
foreach (var col in cols.Elements())
{
foreach (XAttribute at in col.Attributes())
{
if (at.Name.ToString().ToLower().Equals("isactive") && at.Value.ToString() != "true")
{
bAddData = false;
break;
}
bAddData = true;
if (at.Name.ToString().ToLower().Equals("sequence"))
{
sSequence = Convert.ToInt32(at.Value.ToString());
break;
}
}
if (bAddData)
{
columns.Add(col.Name.ToString(), sSequence);
}
}
我确信这是非常糟糕的代码,但我想知道如何改进它。这是xml数据文件。如果我需要重构xml以使其变得简单,我没问题。
<?xml version="1.0" encoding="utf-8" ?>
<datastructure>
<MyPage>
<columns>
<number isactive="true" sequence="1" />
<curr_code isactive="true" sequence="2" />
<curr_desc isactive="true" sequence="3" />
<tradecurrvalue isactive="true" sequence="4" />
<selectcurrvalue isactive="true" sequence="5" />
</columns>
</MyPage>
</datastructure>
答案 0 :(得分:3)
我认为应该这样做:
var doc = XDocument.Load("DataStructure.xml");
var cols = doc.XPathSelectElements("/datastructure/" + sPageName + "/columns");
Dictionary<string, int> columns =
cols.Elements()
.Where(c => c.Attribute("isactive").Value == "true")
.ToDictionary(
c => c.Name.ToString(),
c => Int32.Parse(c.Attribute("sequence").Value)
);
出于好奇,我想知道在没有使用LINQ的情况下可以对原始代码做些什么,一旦我弄清楚它实际上做了什么以及如何最好地使用XElement
类中的方法,我到达了这样:
var doc = XDocument.Load("DataStructure.xml");
var cols = doc.XPathSelectElements("/datastructure/" + sPageName + "/columns");
Dictionary<string, int> columns = new Dictionary<string, int>();
foreach (var col in cols.Elements()) {
if (col.Attribute("isactive").Value == "true") {
columns.Add(col.Name.ToString(), Int32.Parse(col.Attribute("sequence").Value));
}
}
答案 1 :(得分:1)
var doc = XDocument.Load("DataStructure.xml");
var cols = doc.XPathSelectElements("/datastructure/MyPage/columns").Descendants();
var columns = cols.Where(e => e.Attribute("isactive").Value.ToLower() == "true").ToDictionary(e => e.Name, e => int.Parse(e.Attribute("sequence").Value));
答案 2 :(得分:0)
您可以尝试这样的事情
cols.Elements().Where(
e =>
{
var attribute = e.Attribute("isactive");
return attribute != null &&
attribute.Value.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase);
})
.ToDictionary(e => e.Name.ToString(),
e => Convert.ToInt32(e.Attribute("sequence").Value.ToString()));