如何将数组转换为查找数据结构
How to convert an array to a look up data structure
我有一个整数数组,如下所示:
2 2 4 3
我想为以上数据创建一个 Lookup。我希望对于数组中存在的每个唯一数字,我可以将索引维护为一个链接列表,以防它被重复:
2 - 0,1
4 - 2
3 - 3
我通过 LINQ 尝试了一些东西,这似乎是获取 Lookup 实例的标准方法 class 但这不是编译:
var prices = new int[] { 2,2,4,3};
var lookUp = prices.ToLookup<int,int>((x, i) => i + 1);
我不明白为什么我不能像在 Dictionary
class 中那样简单地实例化 Lookup
class 并向其中添加项目。每当它发现再次将相同的键添加到其中时,它应该只是创建一个集合。我推测可以工作的示例代码:
var prices = new int[] { 2,2,4,3};
var lookUp = new Lookup<int,int>();
for (int i = 0; i < prices.Length; i++)
lookUp.Add(prices[i], i);
这又不能像 a note on MSDN 所说的那样编译:
There is no public constructor to create a new instance of a
Lookup. Additionally, Lookup objects
are immutable, that is, you cannot add or remove elements or keys from
a Lookup object after it has been created.
有人可以帮助我获得我的密钥 objective 吗?我正在努力思考如何在 C# 中提供 Lookup
实现。
创建查找的要点是首先将数组中的值映射到数组中的 index/position,然后使用 vlaue 作为键和该值的索引从映射创建查找对于查找项。
以下示例演示将数组转换为所需的查找
using System;
using System.Linq;
public class Program {
public static void Main() {
var prices = new int[] { 2, 2, 4, 3 };
var map = prices.Select((value, index) => new { index, value });
var lookUps = map.ToLookup(_ => _.value, _ => _.index);
foreach(var item in lookUps) {
var value = item.Key;
var indexes = string.Join(",", item);
var output = String.Format("{0} - {1}", value, indexes);
Console.WriteLine(output);
}
}
}
哪个输出
2 - 0,1
4 - 2
3 - 3
对于提供的输入。
我有一个整数数组,如下所示:
2 2 4 3
我想为以上数据创建一个 Lookup。我希望对于数组中存在的每个唯一数字,我可以将索引维护为一个链接列表,以防它被重复:
2 - 0,1
4 - 2
3 - 3
我通过 LINQ 尝试了一些东西,这似乎是获取 Lookup 实例的标准方法 class 但这不是编译:
var prices = new int[] { 2,2,4,3};
var lookUp = prices.ToLookup<int,int>((x, i) => i + 1);
我不明白为什么我不能像在 Dictionary
class 中那样简单地实例化 Lookup
class 并向其中添加项目。每当它发现再次将相同的键添加到其中时,它应该只是创建一个集合。我推测可以工作的示例代码:
var prices = new int[] { 2,2,4,3};
var lookUp = new Lookup<int,int>();
for (int i = 0; i < prices.Length; i++)
lookUp.Add(prices[i], i);
这又不能像 a note on MSDN 所说的那样编译:
There is no public constructor to create a new instance of a Lookup. Additionally, Lookup objects are immutable, that is, you cannot add or remove elements or keys from a Lookup object after it has been created.
有人可以帮助我获得我的密钥 objective 吗?我正在努力思考如何在 C# 中提供 Lookup
实现。
创建查找的要点是首先将数组中的值映射到数组中的 index/position,然后使用 vlaue 作为键和该值的索引从映射创建查找对于查找项。
以下示例演示将数组转换为所需的查找
using System;
using System.Linq;
public class Program {
public static void Main() {
var prices = new int[] { 2, 2, 4, 3 };
var map = prices.Select((value, index) => new { index, value });
var lookUps = map.ToLookup(_ => _.value, _ => _.index);
foreach(var item in lookUps) {
var value = item.Key;
var indexes = string.Join(",", item);
var output = String.Format("{0} - {1}", value, indexes);
Console.WriteLine(output);
}
}
}
哪个输出
2 - 0,1
4 - 2
3 - 3
对于提供的输入。