确定我在阵列中的位置
本文关键字:位置 阵列 | 更新日期: 2023-09-27 17:54:42
我在C#中有一个字符串数组,如下所示:
string[] sites = new string[] {
"http://foobar.com",
"http://asdaff.com",
"http://etc.com"
};
我在foreach
中使用这个数组,我希望能够添加1、2或3的"类型"值,这取决于我当前迭代的站点。我将数据与来自这些站点的StringBuilder
连接起来。现在,我可以将站点存储为varchar
,但它会非常整洁,因为这个数组永远不会改变为将数字与字符串相关联并以这种方式构建它。
使用for
循环而不是foreach
:
for(int i = 0; i < sites.Length; i++)
{
// use sites[i]
}
sites.Select((x, n) => new { Site = x, Index = n })
您可以为此使用字典-Dictionary<int, string>
(或Dictionary<string, int>
(。
var sitesWithId = new Dictionary<string, int>
{
new { "http://foobar.com", 1},
new { "http://asdaff.com", 2},
new { "http://etc.com", 3}
}
另一种选择是只使用List<string>
和IndexOf
来查找索引。
var sites = new List<string> {
"http://foobar.com",
"http://asdaff.com",
"http://etc.com"
};
var foobarIndex = sites.IndexOf("http://foobar.com");
第三种选择,使用Array
的静态IndexOf
方法,并且根本不更改阵列:
var foobarIndex = Array.IndexOf(sites, "http://foobar.com");
尝试使用for
循环;
for(int i = 0; i < sites.Length; i++)
{
Console.WriteLine(sites[i]);
}
用于像这样的CCD_ 13阵列的元素;
sites[1]
sites[2]
sites[3]
或者你可以按照奥德的建议使用Dictionary<TKey, TValue>
。