假设我有一个List<int>很容易搜索整数的问题6
List<int> list = new List<int>(){1, 2, 3, 4, 5};
if(list.Contains(6))
Console.Write("6 exists");
Run Code Online (Sandbox Code Playgroud)
但是我如何int[]在a中搜索aList<int[]>
List<int[]> example = new List<int[]>();
example.Add(new int[4]{0,1,2,3});
example.Add(new int[4]{10,11,12,13});
example.Add(new int[4]{20,21,22,23});
Run Code Online (Sandbox Code Playgroud)
如何{0,1,2,3}在列表中搜索并删除该索引?
int[] toFind = new int[4]{0,1,2,3};
foreach (int[] item in list)
{
if(item.Length == toFind.Length)
{
bool found = false;
for(int i=0; i < item.Length;i++)
{
if(item[i] == toFind[i])
{
found = true;
}
else
{
found = false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图首先将想要的项目长度与每个项目长度进行比较,比较阵列上的每个项目.必须有更好的方法来做到这一点......
你可以使用FindIndex()和Linq扩展SequenceEquals:
int index = list.FindIndex(arr => arr.Length == toFind.Length && arr.SequenceEqual(toFind));
if (index >= 0) list.RemoveAt(index);
Run Code Online (Sandbox Code Playgroud)
请注意,仅当序列中的元素的顺序相同时才SequenceEqual返回true.所以{1,2,3,4}不一样{2,1,4,3}.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |