[英]C# How to display the first, second and third answer only of the combination?
I have coding that uses the combination method. 我有使用组合方法的编码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
string input;
int NoDisplay;
decimal goal;
decimal element;
do
{
Console.WriteLine("Please enter the target:");
input = Console.ReadLine();
}
while (!decimal.TryParse(input, out goal));
Console.WriteLine("Please enter the numbers (separated by spaces)");
input = Console.ReadLine();
string[] elementsText = input.Split(' ');
List<decimal> elementsList = new List<decimal>();
foreach (string elementText in elementsText)
{
if (decimal.TryParse(elementText, out element))
{
elementsList.Add(element);
}
}
int i;
int j;
decimal tmp;
int[] arr1 = new int[10];
for (i = 0; i < elementsList.Count; i++)
{
for (j = i + 1; j < elementsList.Count; j++)
{
if (elementsList[i] < elementsList[j])
{
tmp = elementsList[i];
elementsList[i] = elementsList[j];
elementsList[j] = tmp;
}
}
}
Console.WriteLine("Please enter the maximum combination :");
NoDisplay = Convert.ToInt32(Console.ReadLine());
Solver solver = new Solver();
List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray());
//results.Reverse();
Boolean recordexist = false;
foreach (List<decimal> result in results)
{
if (result.Count == NoDisplay)
{
recordexist = true;
foreach (decimal value in result)
{
Console.Write("{0}\t", value);
}
if (recordexist == true)
{
Console.WriteLine();
}
}
}
if (recordexist == false)
{
Console.WriteLine("No record exist");
}
Console.ReadLine();
}
}
My question is how can i display the first,second and third answer only Like this 我的问题是如何显示的第一,第二和第三个答案只有像这样
Sorry for my bad english, I hope anybody can help me with this. 对不起,我的英语不好,我希望有人可以帮助我。 I still new on c# btw. 我还是C#btw的新手。 Thank you 谢谢
My question is how can i display the first,second and third answer only? 我的问题是我如何仅显示第一,第二和第三答案?
Simply create a counter
variable which increments by 1
each time a sub-list of the results
list has been displayed, when it reaches 3
then we can break
out the loop. 只需创建一个counter
变量,每次显示results
列表的子列表时该counter
变量就增加1
,当它达到3
时,我们就可以break
循环。
int counter = 0;
foreach (List<decimal> result in results)
{
if(counter == 3) break;
if (result.Count == NoDisplay)
{
recordexist = true;
foreach (decimal value in result)
{
Console.Write("{0}\t", value);
}
if (recordexist == true)
{
Console.WriteLine();
}
counter++;
}
}
I would say the simplest option is to use the Linq methods Where
(to filter the results) and Take
(to take the first n results): 我想说的最简单的选择是使用Linq方法Where
(过滤结果)和Take
(获取前n个结果):
var filteredResults = results
.Where(r => r.Count == NoDisplay)
.Take(3);
foreach (var result in filteredResults)
{
foreach (decimal value in result)
{
Console.Write("{0}\t", value);
}
Console.WriteLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.