如何从未知值类型的列表中提取值?

时间:2018-09-23 01:31:31

标签: c#

我似乎无法弄清楚如何将包含子实例列表和包含子实例的元组列表组成的值的s = s.wrap_t(); 转换为作为其父类型(项)的子实例列表,而不调用每个列表明确输入orderedDictionary ...

OrderedDictionary

所以我有一个循环遍历所述字典:

(我尝试使用//Here is a sample of an entry in the OrderedDictionary { "Contextuals", new List<Contextual>{} }, //and some of the entries are lists of tuples; where the int represents an ammount value of "stacked" objects: {"Consumables", new List<Tuple<Consumable,int>>{} }, 的类型代替object,但不确定是否有效,因为我无法在不声明其显式类型的情况下将对象作为列表进行迭代。 )

UnknownListType

如果没有人知道如何实现它,我可能最终会重新制作//convertedList collects all the childinstances as their base type (Item) List<Item> convertedList = new List<Item>(); foreach (KeyValuePair<string, UnknownListType> storedItemCategory in TestDict) { //how would i properly check the value type of an UnknownListType as a list, this is what i would guess would be the way to do it: if (storedItemCategory.Value.GetType().GetGenericArguments()[0].IsSubclassOf(typeof(Item))) { //now how would i convert "storedItemCategory.Value" into a list of items before concatenating it to convertedList? } //else... (extracting the instance of a list of type tuple<UnknownChildInstanceType,int> would be here but isn't really needed to explain the problem) } 本身,使值始终位于同一位置。

1 个答案:

答案 0 :(得分:0)

您的字典必须在某处声明,例如Dictionary 。无论TValueList是什么,它都会告诉您循环变量的类型。您已经写了KeyValuePair …意味着您的字典实际上具有Dictionary 类型,或者您不知道该类型吗?

我的猜测是列表类型TValueList(或您称为UnknownListType)是IList或其他某种非泛型类型。然后,您只需访问该IList并将成员降级为字符串键指示的类型。像这样:

    static public IList<TValue> GetConsolidatedList<TValue>(this Dictionary<string, IList> dictionary)
    {
        IEnumerable<IList> lists = dictionary.Where(kvp => kvp.Key == typeof(TValue).Name).Select(kvp => kvp.Value);
        List<TValue> consolidated = lists.Where( list => list.Count > 0 && list[0] is ValueTuple<TValue,int>).SelectMany(list => list.Cast<(TValue,int)>()).Select( tuple => tuple.Item1).ToList();
        consolidated.AddRange(lists.Where(list => list.Count > 0 && list[0] is TValue).SelectMany(list => list.Cast<TValue>()));
        return consolidated;
    }

请注意,我建议您使用ValueTuple而不是Tuple。这样效率更高,并且还可以使用语法(TValue值,int计数)命名元组的元素

说了这么多,对我来说,最好在结构中使用更多类型信息。最好有两个字典,一个是Dictionary >类型,另一个是Dictionary >类型,然后让您的类实现接口IValue。如果您需要将这两个字典作为一个字典来处理,那么只需将它们都放入一个实现所需操作的类中即可。