2 回答

TA贡献1818条经验 获得超7个赞
一种方法是使用 aDictionary<string, int>将单元格数据存储为键,将映射整数存储为值。
请注意,您不必一次用整个数据集填充映射。只要您维护一个映射字典,您就可以在访问项目时简单地填充它。
请注意,这只会保证字符串的值是唯一的,但在后续运行中不一定是相同的值(因为这些值基于请求 id 的时间而不是字符串本身)。
像这个带有私有字段和访问方法的静态类应该可以工作(尽管不是线程安全的):
public static class Mapper
{
private static readonly Dictionary<string, int> Mapping =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
public static int GetId(string value)
{
int result;
if (!Mapping.TryGetValue(value, out result))
{
result = Mapping.Count + 1;
Mapping.Add(value, result);
}
return result;
}
}
使用此方法,我们可以根据需要获取映射,并且仅在必要时填充字典:
DataTable tbl1 = new DataTable("table1");
tbl1.Columns.Add(new DataColumn("col1"));
tbl1.Columns.Add(new DataColumn("col2"));
tbl1.Columns.Add(new DataColumn("col3"));
tbl1.Columns.Add(new DataColumn("col4"));
tbl1.Columns.Add(new DataColumn("col5"));
tbl1.Columns.Add(new DataColumn("col6"));
tbl1.Columns.Add(new DataColumn("col7"));
tbl1.Columns.Add(new DataColumn("col8"));
tbl1.Columns.Add(new DataColumn("col9"));
tbl1.Columns.Add(new DataColumn("col10"));
tbl1.Rows.Add("abc", "def", "abc", "zxv", "was", "morning", "def", "dr", "tr", "uy");
tbl1.Rows.Add("abc2", "def2", "abc3", "zxv4", "was4", "Morning", "def2", "dr3", "tr3", "uy");
// Output mappings, which populates the dictionary
// only when needed as each mapping is requested
foreach (DataRow row in tbl1.Rows)
{
Console.WriteLine(string.Join(",",
row.ItemArray.Select(item => Mapper.GetId(item.ToString()))));
}
输出

TA贡献1936条经验 获得超7个赞
您可以使用确定性 guid 来创建唯一的哈希。此外,您可以将值本身用作它自己的唯一哈希。如果由于某种原因,您无法向用户显示原始值但仍想在列表中找到它,我只能看到这很有用。例如,一组密码。
[TestMethod]
public void test_sum_stringchars()
{
string tmp = "foobar5";
Console.WriteLine("Value = " + tmp.ToCharArray().Sum(x => x));
// 686
Console.WriteLine("Value = " + ToGuidKey(tmp));
// 79ceeb8d
tmp = "foobar6";
Console.WriteLine("Value = " + tmp.ToCharArray().Sum(x => x));
// 687
Console.WriteLine("Value = " + ToGuidKey(tmp));
// f1f08c51
tmp = "goobar5";
Console.WriteLine("Value = " + tmp.ToCharArray().Sum(x => x));
// 687
Console.WriteLine("Value = " + ToGuidKey(tmp));
// f7da9f42
tmp = "foocar5";
Console.WriteLine("Value = " + tmp.ToCharArray().Sum(x => x));
// 687
Console.WriteLine("Value = " + ToGuidKey(tmp));
// 7698c7ec
}
public static Guid ToGuid(string src)
{
byte[] stringbytes = System.Text.Encoding.UTF8.GetBytes(src);
byte[] hashedBytes = new System.Security.Cryptography
.SHA1CryptoServiceProvider()
.ComputeHash(stringbytes);
Array.Resize(ref hashedBytes, 16);
return new Guid(hashedBytes);
}
public static string ToGuidKey(string src)
{
return ToGuid(src).ToString().Split('-').First();
}
- 2 回答
- 0 关注
- 233 浏览
添加回答
举报