列出LINQ Merge中忽略的重复项

时间:2015-12-15 10:34:59

标签: c# linq dictionary merge

this post开始,是否可以创建合并中找到(和排除)的重复记录的新列表?我想让用户知道哪些记录被排除在外。我的代码是,它正确地合并数据并排除任何重复的键,但我希望能够显示合并后排除的键。

        var fileLocation = @"D:\TFS2010-UK\Merge_Text\PM.INX";
        var fileContents =
            File.ReadLines(FileLocation, Encoding.Default)
                .Select(line => line.Split(','))
                .ToDictionary(line => line[0].Replace("\"", ""), line => line[1] + ',' + line[2] + ',' + line[3]);
        // define an array of items to be added...
        var newContent = new Dictionary<string, string>
                         {
                             { "XYZ789", "\"XYZ789\",1,123.789" },
                             { "GHI456", "\"GHI456\",2,123.456" },
                             { "ABC123", "\"ABC123\",1,123.123" }
                         };

        var uniqueElements = fileContents.Concat(newContent.Where(kvp => !fileContents.ContainsKey(kvp.Key)))
                .OrderBy(x => x.Key)
                .ToDictionary(y => y.Key, z => z.Value);
        // append new lines to the existing file...
        using (var writer = new StreamWriter(fileLocation))
        {
            // loop through the data to be written...
            foreach (var pair in uniqueElements)
            {
                // and write it to the file...
                writer.WriteLine("\"{0}\",{1}", pair.Key, pair.Value);
            }
        }

非常感谢。马丁

1 个答案:

答案 0 :(得分:0)

var removedKeys = newContent.Where(kvp => fileContents.ContainsKey(kvp.Key))
    .Select(kvp => kvp.Key);

只需选择newContent中已包含在fileContents中的键。