如何检查单个数组包含相同的值

时间:2018-07-13 07:04:25

标签: c#

string currentUrl = "destination/India/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";

在上面的示例中,在C#中如何检查国家名称在url中重复?

2 个答案:

答案 0 :(得分:5)

通过Count()出现countryName

string currentUrl = "destination/India/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";
bool isRepeating = array.Count(x => countryName.Equals(x, StringComparison.OrdinalIgnoreCase)) > 1;

答案 1 :(得分:1)

您可以使用Distinct方法。像

string currentUrl = "destination/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";

if (array.Distinct().Count() != array.Count())
{
    Console.WriteLine("Duplicate");
}

或者您可以尝试输入密码

string currentUrl = "destination/india/india/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";

bool r = array.Where(x => x.Equals(countryName)).Count()>1;
if(r)
{
    Console.WriteLine("Duplicate");
}