有人知道如何将列表lst中的剩余元素保存到Stack st中吗?
我已经尝试过if(!new_list.Contains)但它显示了一个错误,我知道我肯定缺少某些东西或只是做错了什么。我是C#的新手,对不起,如果这是一个愚蠢的问题
List<int> lst = new List<int>();
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
lst.Add(rnd.Next(1, 20));
}
List<int> new_lst = lst.FindAll(x => x >= 7 && x <= 12);
Console.WriteLine("");
foreach (int a in new_lst)
{
Console.Write($"{a} ");
}
Stack<int> st = new Stack<int>();
foreach (int a in lst)
{
if ("code")
{
adding remaining elements (that didn't go to new_lst) from lst to st
}
}
我希望数字大于12且小于7
答案 0 :(得分:3)
您可以将条件添加到lst
列表中,以过滤掉new_lst
中包含的项目:
foreach (int a in lst.Where(item => !new_lst.Contains(item)))
{
st.Push(a);
}
话虽如此,只遍历项目一次并将它们添加到完整列表中,然后再添加到新列表或堆栈中(取决于值)会更快:
Random rnd = new Random();
List<int> lst = new List<int>();
List<int> new_lst = new List<int>();
Stack<int> st = new Stack<int>();
for (int i = 0; i < 10; i++)
{
var thisItem = rnd.Next(1, 20);
lst.Add(thisItem);
if (thisItem >= 7 && thisItem <= 12)
{
new_lst.Add(thisItem);
}
else
{
st.Push(thisItem);
}
}
答案 1 :(得分:1)
最简单的方法是在遍历列表时将项目添加到一个或另一个:
foreach (int x in lst)
{
if (x >= 7 && x <= 12)
new_lst.add(x);
else
st.Push(a);
}
如果您想使用更奇特的路线,我将保存条件并选择要列出/堆叠具有相反条件的项目
Func<int,bool> filter = x => x >= 7 && x <= 12;
var new_lst = lst.Where(filter).ToList();
var st = new Stack<int>(lst.Where(x=> !filter(x));