问题描述
我有一个功能,成块读取文件。
I have a function that reads a file in chunks.
public static DataObject ReadNextFile(){ ...}
和数据对象是这样的:
public DataObject
{
public string Category { get; set; }
// And other members ...
}
我想要做的是以下基本
List<DataObject> dataObjects = new List<DataObject>();
while(ReadNextFile().Category == "category")
{
dataObjects.Add(^^^^^ the thingy in the while);
}
我知道这可能不是它是如何做的,因为我怎么访问对象我刚读。
I know it's probably not how it's done, because how do I access the object I've just read.
推荐答案
我想你要找的是:
List<DataObject> dataObjects = new List<DataObject>();
DataObject nextObject;
while((nextObject = ReadNextFile()).Category == "category")
{
dataObjects.Add(nextObject);
}
但我不会那样做。我会写:
But I wouldn't do that. I'd write:
List<DataObject> dataObject = source.ReadItems()
.TakeWhile(x => x.Category == "Category")
.ToList();
其中, ReadItems()
发回的方法一个的IEnumerable<&数据对象GT;
,读,同时产生一个项目。你可能想用迭代器块来实现它(收益回报率
等)。
where ReadItems()
was a method returning an IEnumerable<DataObject>
, reading and yielding one item at a time. You may well want to implement it with an iterator block (yield return
etc).
这是假设你真的要停止尽快看完,你觉得它有不同的类别的第一个对象。如果你真的要包括的所有的匹配数据对象
S,
变动 TakeWhile
到其中,
在上面的LINQ查询
This is assuming you really want to stop reading as soon as you find the first object which has a different category. If you actually want to include all the matching DataObject
s,change TakeWhile
to Where
in the above LINQ query.
(编辑:赛义德后来删掉了他反对的答案,但我想我还不如离开的例子了......)
( Saeed has since deleted his objections to the answer, but I guess I might as well leave the example up...)
编辑:证明,这将工作,因为赛义德似乎不相信我的话:
Proof that this will work, as Saeed doesn't seem to believe me:
using System;
using System.Collections.Generic;
public class DataObject
{
public string Category { get; set; }
public int Id { get; set; }
}
class Test
{
static int count = 0;
static DataObject ReadNextFile()
{
count++;
return new DataObject
{
Category = count <= 5 ? "yes" : "no",
Id = count
};
}
static void Main()
{
List<DataObject> dataObjects = new List<DataObject>();
DataObject nextObject;
while((nextObject = ReadNextFile()).Category == "yes")
{
dataObjects.Add(nextObject);
}
foreach (DataObject x in dataObjects)
{
Console.WriteLine("{0}: {1}", x.Id, x.Category);
}
}
}
输出:
Output:
1: yes
2: yes
3: yes
4: yes
5: yes
在换句话说,该列表保留引用已经从返回的5个不同的对象 ReadNextFile
。
In other words, the list has retained references to the 5 distinct objects which have been returned from ReadNextFile
.
这篇关于在while循环变量initalisation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!