按键向通用词典添加值
本文关键字:添加 通用词 | 更新日期: 2023-09-27 18:35:50
我有一个通用字典,我用一个键,但一个空值,因为我需要在迭代中构建值,该值只能在之后添加到唯一键中。
我的问题,有没有一种优雅的方法可以通过它的键将实例化的集合添加到字典中?
我的情况:
值存储在记录的描述块集合中
[1]|[Category reference]
[2]|[Category reference]
[3]|[Category reference]
[1]|[Category reference 1]
[2]|[Category reference 2]
由此,我对管道 {|} 项进行拆分,然后拉取类别值并将其添加到实体对象中,每次迭代:
// I have a dictionary object to be used for categorization
Dictionary<string, List<FieldItem>> dict =
new Dictionary<string, List<FieldItem>>();
// need to store each field item in a List<T>
List<FieldItem> items = new List<FieldItem>();
// then I iterate each record from my data source,
// and get the category from description
foreach (var item in records)
{
string category = item.Description
.Split(new char[] { '|' })[1]
.Trim(new char[] { '[', ']');
// this will give me the category for each item
FieldItem fi = new FieldItem { Category = category }; // more items will be added
if (!dict.Keys.Contains(category))
dict.Add(category, null);
items.Add(fi);
}
// now, I have the List<FieldItem> collection and
// each one contains a category, I now need to add this List<FieldItem>
// collection to Dictionary<string, List<FieldItem>> based on the
// category, so I tried this:
foreach (var kvp in dict.Keys)
{
var addItem = items.Where(x => x.Category.Equals(kvp)).ToList(); // gives me collection
// would it be elegant to delete the key from the collection first?
// cannot do a delete here as the Dictionary is in use, so
// thought of adding my items to a new Dictionary??
dict.Add(kvp, addItem);
}
foreach (var item in records)
{
string category = item.Description
.Split(new char[] { '|' })[1]
.Trim(new char[] { '[', ']');
// this will give me the category for each item
FieldItem fi = new FieldItem { Category = category }; // more items will be added
if (!dict.Keys.Contains(category))
dict.Add(category, new List<FieldItem>());
dict[category].Add(fi);
}