可能重复:
有机会使用 Linq (C#) 获得唯一记录吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WaysOf100
{
class WaysOf100Test
{
static void Main(string[] args)
{
WaysOf100 test= new WaysOf100();
test.Go();
test.EliminateDuplicates();
}
}
class WaysOf100
{
List<string> results = new List<string>();
public void Go()
{
int num = 5, temp=0;//to store the intermediate difference
for (int i = 1; i <num; i++)
{
temp = num - i;
for (int j = 1; j <= temp; j++)
{
if (temp % j == 0)
{
//Console.Write(i + " ");
string text = "";
text = i.ToString();
for (int k = 1; k <= (temp / j); k++)
{
//Console.Write(j + " ");
text += j.ToString();
}
char[] rev = text.ToCharArray();
Array.Reverse(rev);
if(!(results.Contains(rev.ToString())))
results.Add(text);
}
}
}
}
public void EliminateDuplicates()
{
//To eliminate the duplicates
/*for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char [] rev = results[j].ToCharArray();
Array.Reverse(rev);
if (results[i]==rev.ToString())
results.Remove(rev.ToString());
}
}
}*/
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is :{0}",results.Count);
}
}
}
到目前为止的结果是 11111 122 14 2111 23 311 32 41
简而言之,这就是我想要的:41 的倒数是 14,而 14 已经存在于列表中,所以我不想添加 41。同样,32 的倒数是 23,它也存在,因此不应添加 32。但是我为实现该功能而编写的这个可能并没有给出预期的结果
if(!(results.Contains(rev.ToString())))
results.Add(text);