0

我有一个通用字典,我用一个键实例化,但是一个空值,因为我需要在迭代之外构建值,该值只能在之后添加到唯一键。

我的问题是,有没有一种优雅的方法可以通过键将实例化集合添加到字典中?

我的情况:

值存储在记录的描述块集合中

[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);
}
4

1 回答 1

2
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);   
}
于 2013-10-18T08:47:46.853 回答