我有一个方法,其中包含IDictionary<string, IEnumerable<string>> collection
作为参数
void find(IDictionary<string, IEnumerable<string>> collection)
{
// I need to remove some values, like this
collection[element].Remove(element[element.Count - 1]);
}
当我可以删除一些元素时,如何将此参数转换为某种状态?
答案 0 :(得分:2)
您可以做的是这样的:如果Dictionary<,>
的值是IList<>
,那么您可以直接RemoveAt
,否则将其转换为IList<>
,删除元素并替换Dictionary<,>
void find(IDictionary<string, IEnumerable<string>> collection, string element)
{
// I need to remove some values, like this
IEnumerable<string> value = collection[element];
IList<string> ilist = value as IList<string>;
if (ilist != null && !(value is string[]))
{
// Remove the last element
ilist.RemoveAt(ilist.Count - 1);
}
else
{
ilist = value.ToList();
ilist.RemoveAt(ilist.Count - 1);
collection[element] = ilist;
}
}
警告强>
这种方法的工作有点精神分裂。如果有人在调用IEnumerable<>
之前保存了对find
之一的引用,那么find
之后的引用可能是与该引用相同或不同的集合。 Dictionary<,>
(取决于find
是否必须重新创建它或者是否可以重复使用它)。
一个例子:
var dict = new Dictionary<string, IEnumerable<string>>
{
{ "Foo", new string[] { "Foo1", "Foo2" } },
};
var lst1 = dict["Foo"];
find(dict, "Foo");
var lst2 = dict["Foo"]; // lst1 and lst2 reference DIFFERENT collections
find(dict, "Foo");
var lst3 = dict["Foo"]; // lst2 and lst3 reference THE SAME collection
和
var dict = new Dictionary<string, IEnumerable<string>>
{
{ "Foo", new List<string> { "Foo1", "Foo2" } },
};
var lst1 = dict["Foo"];
find(dict, "Foo");
var lst2 = dict["Foo"]; // lst1 and lst2 reference THE SAME collection
find(dict, "Foo");
var lst3 = dict["Foo"]; // lst2 and lst3 reference THE SAME collection