写循环,对第一项特殊的逻辑集合中巧妙的方法 [英] Neat way to write loop that has special logic for the first item in a collection
本文介绍了写循环,对第一项特殊的逻辑集合中巧妙的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常不得不代码,有特殊情况的集合中的第一项循环,代码似乎从来没有一个明确的,它应该是。
短C#语言的重新设计,什么是这些代码循环的最佳方式?
//这是更多的代码读取,然后我想对于这样一个共同的概念,
//它是容易忘记更新与firstItem
的foreach(在YYY X)
{
如果(与firstItem)
{
=与firstItem虚假的;
//其他代码时,第一个项目
}
//正常的处理代码
}
//这个代码是更难理解
如果(yyy.Length大于0)
{
//处理第一个项目;
的for(int i = 1; I< yyy.Length;我++)
{
//过程中的其他项目。
}
}
解决方案
您可以尝试:
collection.first(X =>
{
// ...
})休息(X =方式>
{
// ...
})运行();
第一/其余的将是这样的:
FirstPart< T>第一< T>(这个IEnumerable的< T&℃,动作< T>一种)
{
返回新FirstPart< T>(C,A);
}
FirstRest休息< T>(这FirstPart< T> FP,动作< T>一种)
{
返回新FirstRest(fp.Collection,FP .Action,一);
}
您需要定义归类FirstPart和FirstRest。 FirstRest需要像这样一个run方法(收集,FirstAction和RestAction是属性):
无效的run()
{
布尔第一= TRUE;
的foreach(在集合变种X)
{
如果(第一){
FirstAction(X);
第一= FALSE;
}
,否则{
RestAction(X);
}
}
}
Often I have to code a loop that has to special case the first item in a collection, the code never seems a clear as it should be.
Short of a redesign of the C# language, what is the best way to code these loops?
// this is more code to read then I would like for such a common concept
// and it is to easy to forget to update "firstItem"
foreach(x in yyy)
{
if (firstItem)
{
firstItem = false;
// other code when first item
}
// normal processing code
}
// this code is even harder to understand
if (yyy.Length > 0)
{
//Process first item;
For(int I = 1; I <yyy.Length; i++)
{
// process the other items.
}
}
解决方案
You could try:
collection.first(x=>
{
//...
}).rest(x=>
{
//...
}).run();
first / rest would look like:
FirstPart<T> first<T>(this IEnumerable<T> c, Action<T> a)
{
return new FirstPart<T>(c, a);
}
FirstRest rest<T>(this FirstPart<T> fp, Action<T> a)
{
return new FirstRest(fp.Collection, fp.Action, a);
}
You would need to define classed FirstPart and FirstRest. FirstRest would need a run method like so (Collection, FirstAction, and RestAction are properties):
void run()
{
bool first = true;
foreach (var x in Collection)
{
if (first) {
FirstAction(x);
first = false;
}
else {
RestAction(x);
}
}
}
这篇关于写循环,对第一项特殊的逻辑集合中巧妙的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文