gpt4 book ai didi

c# - XML 排序在 ASP.NET MVC 中使用 LINQ

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:05 26 4
gpt4 key购买 nike

我正在尝试对 xml 文件中的某些列进行排序。这是我的。

    public ActionResult Index(string sortOrder)
{
IEnumerable<Personal> personals;
XmlDocument doc = new XmlDocument();
List<Personal> persons = new List<Personal>();
doc.Load("C:\\Users\\Matt.Dodson\\Desktop\\SampleWork\\PersonsApplicationFromXMLFile\\PersonsApplicationFromXMLFile\\DAL\\Personal.xml");
foreach (XmlNode node in doc.SelectNodes("/Persons/record"))
{
persons.Add(new Personal
{
ID = node["ID"].InnerText,
Name = node["Name"].InnerText,
Email = node["Email"].InnerText,
DateOfBirth = node["DateOfBirth"].InnerText,
Gender = node["Gender"].InnerText,
City = node["City"].InnerText
});
}
switch (sortOrder)
{
case "ID":
personals = persons.OrderBy(Personal => Personal.ID);
break;
case "Name":
personals = persons.OrderBy(Personal => Personal.Name);
break;
case "City":
personals = persons.OrderBy(Personal => Personal.City);
break;
default:
break;
}
return View(persons);
}

我尝试过的方法包括 .getElementByTagName("ID").toString().OrderBy(...),但无济于事。我很确定我的语法全错了。请帮忙,谢谢。

最佳答案

我认为你需要让 was sorted 集合结果设置为 persons否则,该集合未被排序。

switch (sortOrder)
{
case "ID":
persons = persons.OrderBy(Personal => Personal.ID).ToList();
break;
case "Name":
persons = persons.OrderBy(Personal => Personal.Name).ToList();
break;
case "City":
persons = persons.OrderBy(Personal => Personal.City).ToList();
break;
default:
break;
}
return View(persons);

我会使用 linq而不是 foreach让代码更清晰。

SelectNodes("/Persons/record").Cast<XmlNode>()使用 Cast<XmlNode>()XmlNodeListIEnumerable<XmlNode>收集然后使用linq select .

public ActionResult Index(string sortOrder)
{
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Matt.Dodson\\Desktop\\SampleWork\\PersonsApplicationFromXMLFile\\PersonsApplicationFromXMLFile\\DAL\\Personal.xml");
IEnumerable<Personal> persons = doc.SelectNodes("/Persons/record")
.Cast<XmlNode>()
.Select(node => new Personal()
{
ID = node["ID"].InnerText,
Name = node["Name"].InnerText,
Email = node["Email"].InnerText,
DateOfBirth = node["DateOfBirth"].InnerText,
Gender = node["Gender"].InnerText,
City = node["City"].InnerText
});
switch (sortOrder)
{
case "ID":
persons = persons.OrderBy(Personal => Personal.ID);
break;
case "Name":
persons = persons.OrderBy(Personal => Personal.Name);
break;
case "City":
persons = persons.OrderBy(Personal => Personal.City);
break;
default:
break;
}
return View(persons.ToList());
}

关于c# - XML 排序在 ASP.NET MVC 中使用 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com