如何填充一个字典对象
本文关键字:一个 字典 对象 填充 何填充 | 更新日期: 2023-09-27 18:01:21
我以前就有过这个,我去掉了KVP,只剩下Dictionary属性。
:
public class GranuleAttributes
{
public Dictionary<string, KVP> attributes { get; set; }
}
public class KVP
{
public string ID { get; set; }
public string Value { get; set; }
}
:
public class GranuleAttributes
{
public Dictionary<string, string> attributes { get; set; }
}
在我用以下LINQ填充我的字典之前:
attributes =
(
from attrRow in granuleGroup.First()
select new KVP()
{
ID = Convert.ToString(attrRow["AttributeID"],
Value = (string)attrRow["AttributeValue"]
}
).ToDictionary(p => p.ID)
我现在如何填充我的属性对象?
更新好的,完全披露,下面是代码:
var groups = reader.Cast<IDataRecord>()
.GroupBy(dr => new { ID = (int)dr["id"] })
.GroupBy(g => g.Key.ID);
response.attributes = (
from granuleGroup in groups
let granuleRow = granuleGroup.First().First()
select new USpaceDataAttributes()
{
id = (int)granuleRow["id"],
endDate = Convert.ToDateTime(granuleRow["endDate"]),
startDate = Convert.ToDateTime(granuleRow["startDate"]),
type = !DBNull.Value.Equals(granuleRow["type"]) ? (string)granuleRow["type"] : "",
attributes =
(
from attrRow in granuleGroup.First()
select new KVP()
{
ID = !DBNull.Value.Equals(attrRow["AttributeID"]) ? Convert.ToString(attrRow["AttributeID"]) : string.Empty,
Value = !DBNull.Value.Equals(attrRow["AttributeValue"]) ? (string)attrRow["AttributeValue"] : string.Empty
}
).ToSerializableDictionary(p => p.ID)
}
).ToList();
然后我有我自己的类,像public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
与以下扩展方法。
#region ExtensionMethod
public static class CollectionExtensions
{
public static SerializableDictionary<TKey, T> ToSerializableDictionary<TKey, T>(this IEnumerable<T> seq, Func<T, TKey> keySelector)
{
var dict = new SerializableDictionary<TKey, T>();
foreach (T item in seq)
{
TKey key = keySelector(item);
dict.Add(key, item);
}
return dict;
}
}
#endregion
我认为你不需要选择匿名对象或KVP对象
attributes = granuleGroup.First()
.ToDictionary(r => Convert.ToString(r["AttributeID"]),
r => Convert.ToString(r["AttributeValue"]));
更新:你应该添加值选择器到你的扩展方法
public static class CollectionExtensions
{
public static SerializableDictionary<TKey, TValue> ToSerializableDictionary<T, TKey, TValue>(
this IEnumerable<T> source, Func<T, TKey> keySelector, Func<T, TValue> valueSelector)
{
var dict = new SerializableDictionary<TKey, TValue>();
foreach (T item in source)
{
TKey key = keySelector(item);
TValue value = valueSelector(item);
dict.Add(key, value);
}
return dict;
}
}
attributes =
(
from attrRow in granuleGroup.First()
select new {
Key = Convert.ToString(attrRow["AttributeID"],
Value = (string)attrRow["AttributeValue"]
}
).ToDictionary(p => p.Key, p => p.Value)