我有一个字符串列表,使用特定方法进行排序:
list1 : { "E", "C", "B", "A"};
现在我想检查其他数组,如果它是按照list1排序的,那么它是正确的。
例如:
array: { "A", "C", "E", "B" } //false - not ordered according to list1
array: { "E", "B", "C" } //false - not ordered according to list1
array: { "C", "A"} //true- ordered according to list1
功能代码:
List<string> list1 = new List<string> { "E", "C", "B", "A"};
public static bool IsSorted(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
if () //Your opinion
{
return false;
}
}
return true;
}
答案 0 :(得分:4)
我认为使用Lists而不是数组
很容易以下是一个例子:
List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
list1.Add(3);
List<int> list2 = new List<int>();
list2.Add(2);
list2.Add(3);
Console.WriteLine( list1.Intersect(list2).SequenceEqual(list2)); // Will return true
根据您的示例发布关于int变量的示例,您可以使用您想要的任何类型
UPDATE :它也适用于数组(感谢@Matthew Watson)
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 2, 3 };
Console.WriteLine( arr1.Intersect(arr2).SequenceEqual(arr2)); // will return true
答案 1 :(得分:1)
对于案例<=
({ "E", "E" }
是true
),这很简单:
static List<string> list1 = new List<string> { "E", "C", "B", "A" };
// Uses a <= algorithm, so "E", "E" is true
public static bool IsSorted(IEnumerable<string> enu)
{
// index of last letter used in list1
int lastIndex = 0;
foreach (string str in enu)
{
// Start searching from the last index found
int index = list1.IndexOf(str, lastIndex);
// index == -1 means not found
if (index == -1)
{
return false;
}
lastIndex = index;
}
return true;
}
代码中的评论。
如果您需要<
,那么{ "E", "E" }
为false
:
// Uses a < algorithm, so "E", "E" is false
public static bool IsSorted(IEnumerable<string> enu)
{
// Note that we have a +1 in the IndexOf to balance the -1 here
int lastIndex = -1;
foreach (string str in enu)
{
// Start searching from the last index found + 1
int index = list1.IndexOf(str, lastIndex + 1);
// index == -1 means not found
if (index == -1)
{
return false;
}
lastIndex = index;
}
return true;
}
答案 2 :(得分:0)
您可以使用两种LINQ方法:Intersect来获取两个列表共有的项目;然后SequenceEqual检查两个列表是否具有相同顺序的相同项目。所以:
listToCheck.Intersect(list1).SequenceEqual(listToCheck)