使用LINQ将项目推入堆栈 [英] Pushing Items into stack with LINQ
问题描述
我如何以编程方式将字符串数组推入通用堆栈?
How can i programatically push an array of strings into generic Stack ?
字符串数组
string[] array=new string[]{"Liza","Ana","Sandra","Diya"};
堆栈设置
public class stack<T>
{
private int index;
List<T> list;
public stack()
{
list = new List<T>();
index=-1;
}
public void Push(T obj)
{
list.Add(obj);
index++;
}
...........
}
我需要在这里做些什么更改?
stack<string> slist = new stack<string>();
var v = from vals in array select (p => slist.Push(p));
错误报告:
The type of the expression in the select clause is incorrect.
推荐答案
LINQ是一种查询语言/框架.您要在此处执行的是对集合对象的修改,而不是查询(选择)-这肯定不是LINQ设计(甚至能够)的 not
LINQ is a query language/framework. What you want to perform here is a modification to a collection object rather than a query (selection) - this is certainly not what LINQ is designed for (or even capable of).
但是,您可能想为Stack<T>
类定义一个扩展方法.请注意,在这里使用BCL Stack<T>
类型(正是您所需要的)也是有意义的,而不是使用List<T>
重新发明轮子.
What you might like to do, however, is to define an extension method that for the Stack<T>
class, however. Note that it also makes sense to here to use the BCL Stack<T>
type, which is exactly what you need, instead of reinventing the wheel using List<T>
.
public static void PushRange<T>(this Stack<T> source, IEnumerable<T> collection)
{
foreach (var item in collection)
source.Push(item);
}
然后允许您执行以下操作:
Which would then allow you do the following:
myStack.PushRange(myCollection);
如果您还没有确信,那么还有另一个哲学原因:LINQ的创建是为了将功能性范例引入C#/.NET,而功能性编程的核心是无副作用的代码.因此,将LINQ与状态修改代码结合在一起将非常不一致.
And if you're not already convinced, another philosophical reason: LINQ was created to bring functional paradigms to C#/.NET, and at the core of functional programming is side-effect free code. Combining LINQ with state-modifying code would thus be quite inconsistent.
这篇关于使用LINQ将项目推入堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!