我在一个二进制文件中有大量数据记录,我想在其中搜索一些东西。有什么方法可以在文件数据上使用 LINQ 语句而不将所有数据放入内存(如List<T>
)?
我有这种使用方法List<Book>
:
private Book Read(long position)
{
Book book;
using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read))
{
st.Position = position;
using (BinaryReader reader = new BinaryReader(st))
{
if (!reader.ReadBoolean())
return null;
book = new Book()
{
Id = reader.ReadInt32(),
Name = reader.ReadString(),
Dewey = reader.ReadString()
};
try
{
book.Subject = reader.ReadString();
book.RegDate = reader.ReadInt32();
book.PubDate = reader.ReadInt32();
}
catch (EndOfStreamException) { }
}
}
return book;
}
private List<Book> getAll( int recordLength = 100)//sorted results by Id!!
{
long Len;
using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read))
{
Len = st.Length;
}
List<Book> res = new List<Book>();
Book ReadedBook = null;
for (int i = 0; i < Len/100; i++)
{
ReadedBook = Read(i * 100);
if (ReadedBook != null)
res.Add(ReadedBook);
}
res.Sort((x, y) => x.Id.CompareTo(y.Id));
return res;
}