爲什麼不只是讓GetKey()以字符串形式返回鍵?
var a = dt.AsEnumerable().GroupBy(e => new { name = e[GetKey(e)] });
可以在指定的列創建從價值的關鍵,並使其成爲一個字符串組:
var keyDictionary = new Dictionary<string, IEnumerable<string>>();
keyDictionary.Add("Table1", new List<string> {"Group", "Position"});
var dt = new DataTable("Table1");
dt.Columns.AddRange(new [] { new DataColumn("Id", typeof(int)), new DataColumn("Group", typeof(string)), new DataColumn("Position", typeof(string)), new DataColumn("Name", typeof(string))});
var rowItemArrays = new [] { new object[] { 1, "Alpha", "Left", "Bob" }, new object[] { 2, "Alpha", "Right", "Mary"}, new object[] { 3, "Beta", "Right", "Bill"}, new object[] { 4, "Alpha", "Right", "Larry"}};
rowItemArrays.ToList().ForEach(i => dt.Rows.Add(i));
Func<DataRow, string> GetKeys = (dataRow) => string.Join("", keyDictionary[dataRow.Table.TableName].Select(key => dataRow[key].ToString()).ToArray());
var a = dt.AsEnumerable().GroupBy(GetKeys);
你不得不注意空值等..
想到這一點,我沒有去用它,因爲我在迭代linq查詢結果時使用了字典數據。我想我仍然可以將所有值附加到單個字符串中,並將其解析爲鍵/值對。 – toasteroven 2009-10-15 22:16:30
好的,我添加了一些適合我的東西。 – 2009-10-16 00:02:49