2 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超7個贊
一種方法是使用 aDictionary<string, int>將單元格數(shù)據(jù)存儲為鍵,將映射整數(shù)存儲為值。
請注意,您不必一次用整個數(shù)據(jù)集填充映射。只要您維護一個映射字典,您就可以在訪問項目時簡單地填充它。
請注意,這只會保證字符串的值是唯一的,但在后續(xù)運行中不一定是相同的值(因為這些值基于請求 id 的時間而不是字符串本身)。
像這個帶有私有字段和訪問方法的靜態(tài)類應(yīng)該可以工作(盡管不是線程安全的):
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;
}
}
使用此方法,我們可以根據(jù)需要獲取映射,并且僅在必要時填充字典:
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貢獻(xiàn)1936條經(jīng)驗 獲得超7個贊
您可以使用確定性 guid 來創(chuàng)建唯一的哈希。此外,您可以將值本身用作它自己的唯一哈希。如果由于某種原因,您無法向用戶顯示原始值但仍想在列表中找到它,我只能看到這很有用。例如,一組密碼。
[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 關(guān)注
- 218 瀏覽
添加回答
舉報