c# - 从不同的 IEnumerable 映射 KeyValuePair

标签 c# algorithm linq lambda

问题:

我需要将我的 reducedList 中的数据与我的 coreList 相匹配,某种连接,其中键(“Year, Id, House... ") 的 reducedList 将与我的 coreList 的键(列表)匹配,这 2 个结果将合并到临时结果列表 tempList-这将是一栏。

最终目标是用我后来合并的数据来填充整个excel列,其中tempList中的第一个条目是标题,其余是数据。

源码已注释掉,希望对你有帮助。

一开始我的示例有效,但我需要一种更好的方法,也许性能更高或解决问题的不同方法,我认为我需要一种更好的映射方法/算法。

这是我的方法:

核心数据(一切):

Dictionary<String, Object> coreList = (Dictionary<String, Object>)_rawCoreList
    .Where(x => x.Key.Equals("ListOfCities"))
    .ToDictionary(x => x.Key, x => x.Value);//filter the property out I need

初始化数据(此列表稍后将与 coreList 匹配):

List<KeyValuePair<String, String>> reducedList = new List<KeyValuePair<string, string>>();

reducedList.Add(new KeyValuePair<string, string>("Id", "1. Heading"));
reducedList.Add(new KeyValuePair<string, string>("Year", "2. Heading"));
reducedList.Add(new KeyValuePair<string, string>("House", "3. Heading"));
reducedList.Add(new KeyValuePair<string, string>("Garage", "4. Heading"));
reducedList.Add(new KeyValuePair<string, string>("Basdlf", "The key does not exist"));
//reducedList.Add(new KeyValuePair<string, string>(null, null));//check for strange data

将精简列表(只有少数属性)中的属性名称与核心列表(所有属性)组合/匹配:

List<KeyValuePair<String/* Property-Name */, object /* Werte Property-Name */>> ergebnisListe = new List<KeyValuePair<string, object>>();//"" daraus ein Array machen

#region Matching with the reduced list

foreach (KeyValuePair<string, String> reducedListItem in reducedList)
{
    List<string> tempList = new List<string>();

    tempList.Add(reducedListItem.Value != null && !String.IsNullOrEmpty(reducedListItem.Value) ? reducedListItem.Value : "!Überschrift_FEHLER!");//adding the heading first

    #region Itereating through the core list, to get the rest for my data set(actually I need some mapping)

    foreach (KeyValuePair<string, Object> item in coreList)
    {
        #region Filter for my desired list

        if (item.Value is IEnumerable && item.Value.GetType().IsGenericType) //matching only for lists, I expect to work with
        {
            foreach (Dictionary<string, object> subItemListItem in item.Value as List<object>)// I am exspecting some kind of list with "KeyValuePair"'s
            {
                if (subItemListItem.ContainsKey(reducedListItem.Key))//checking for valid keys
                {
                    //doing something with "subItemListItem.Values" or "Keys" ?!
                    tempList.Add(subItemListItem[reducedListItem.Key] != null ? subItemListItem[reducedListItem.Key].ToString() : "ERROR");
                }
            }
        }

        #endregion

    }

    #endregion

    #region Adding the result to my final list

    // adding one column/record
    ergebnisListe.Add(new KeyValuePair<string, object>(reducedListItem.Key, tempList.ToArray())); //I need "string[]" first record is the heading and the rest is it's related data

    #endregion
}

除了核心列表,我几乎可以随意更改数据结构和类型。

感谢您的帮助。

最佳答案

这是一个 LINQ 版本:

// Getting dictionaries from coreList
var dictsInCoreList =
    coreList
        .Values
        .Where(value => value is IEnumerable && value.GetType().IsGenericType)
        .SelectMany(value => value as List<object>)
        .Cast<Dictionary<string, object>>()
        .ToList();

// Generate the result
ergebnisListe =
    reducedList
        .Select(reducedListItem =>
            {
                var tempList =
                    new List<string>()
                    {
                        String.IsNullOrEmpty(reducedListItem.Value)
                            ? "!Überschrift_FEHLER"
                            : reducedListItem.Value
                    };

                tempList.AddRange(
                    dictsInCoreList
                        .Where(dict => dict.ContainsKey(reducedListItem.Key))
                        .Select(dict => dict[reducedListItem.Key]?.ToString() ?? "ERROR")
                );

                return new KeyValuePair<string, object>(reducedListItem.Key, tempList);
            }
        )
        .ToList();

由于在第一个语句中收集了所有字典,所以速度更快。

但是我认为有些东西需要重构,因为如果 coreList仅包含列表(这样我们就不需要过滤 .Value 属性的类型)那么它的真实类型将是 Dictionary<string, List<Dictionary<string, object>>>这对我来说有点味道。

但是,如果目前对您的解决方案没有更多的领域知识,我无法建议更好的映射。

关于c# - 从不同的 IEnumerable 映射 KeyValuePair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36939758/

相关文章:

c# - PetaPoco.Database 实现了 IDisposable,那么为什么大多数示例没有 'using' 语句?

algorithm - 需要帮助找出要使用的算法

algorithm - 随机数递归

c# - 从 LINQuery 获取单个元素?

c# - 使用循环转换此 linq 表达式

c# - 打开封闭的表格

C#:自定义排序的 DataGridView

c# - 类未按预期序列化

algorithm - 在 Delaunay 三角剖分中重新定位点

linq - 使用 LINQ 时我们应该使用 3 层吗?