如果我有这个数据模型类:
public class Person
{
private int _id;
private int _deptID;
private string _firstName;
private string _lastName;
public int ID
{
get { return _deptID; }
set { _deptID = value; }
}
public int DeptID
{
get { return _id; }
set { _id = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
...然后创建我的数据集
private List<Person> GeneratePersonData()
{
List<Person> personData = new List<Person>();
personData.Add(new Person() { ID = 1, DeptID = 25, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 2, DeptID = 25, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 3, DeptID = 105, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 4, DeptID = 43, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 5, DeptID = 25, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 6, DeptID = 32, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 7, DeptID = 2, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 8, DeptID = 25, FirstName = "John", LastName = "Doe" });
personData.Add(new Person() { ID = 9, DeptID = 2, FirstName = "John", LastName = "Doe" });
return personData;
}
然后我将数据存储到 xml 中,如下所示:
private void StorePersonData()
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Person.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, GeneratePersonData());
}
}
}
}
现在,我想要做的是只将 xml 中具有特定 deptID 的人读入一个新列表,所以我这样做:
private void ReadPersonData(int deptID)
{
List<Person>data = new List<Person>();
List<Person> newData = new List<Person>();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Person.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
data = (List<Person>)serializer.Deserialize(stream);
}
}
for (int i = 0; i < data.Count; i++)
{
if (data[i]._deptID == deptID)
{
newData.Add(data[i]);
}
}
}
}
但是如果我有一个非常大的数据集,这种方法会非常慢。xml中有没有办法只读取满足特定条件的数据?