You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dictionary<string,List<object>>中去重及处理ParameterDetails列表重复参数问题

Got it, let's tackle these two duplicate-handling scenarios step by step. I'll break down solutions for both your requirements with code examples and explanations tailored to common use cases.

Solution for Handling Duplicates in Two Scenarios

1. Replacing Duplicates in Dictionary<string, List<object>> with Unique Strings

Since we're dealing with generic object types, we first need a reliable way to detect duplicate content. A common approach is to serialize each object to a consistent string (like JSON) to compare their values. Then, we can track seen objects and replace duplicates with a unique identifier string.

Here's a C# implementation using System.Text.Json for serialization:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

public static class DictionaryDuplicateHandler
{
    public static Dictionary<string, List<object>> ReplaceDuplicatesWithUniqueStrings(Dictionary<string, List<object>> inputDict)
    {
        var resultDict = new Dictionary<string, List<object>>();
        // Use compact serialization to ensure consistent comparison
        var serializeOptions = new JsonSerializerOptions { WriteIndented = false };

        foreach (var (key, items) in inputDict)
        {
            var seenObjectHashes = new HashSet<string>();
            var processedList = new List<object>();
            int duplicateCounter = 1;

            foreach (var item in items)
            {
                string itemHash = JsonSerializer.Serialize(item, serializeOptions);
                
                if (seenObjectHashes.Add(itemHash))
                {
                    // Unique item: keep it as-is
                    processedList.Add(item);
                }
                else
                {
                    // Duplicate: replace with a unique string
                    processedList.Add($"Duplicate_{key}_{duplicateCounter++}");
                }
            }

            resultDict.Add(key, processedList);
        }

        return resultDict;
    }
}

Notes:

  • If your objects aren't JSON-serializable, you could implement a custom IEqualityComparer<object> to define what counts as a duplicate.
  • The unique string includes the dictionary key and a counter to ensure uniqueness even if duplicates appear across different dictionary entries.

2. Ensuring Unique Parameter Names in List<ParameterDetails>

Since your requirement doesn't specify how to handle duplicates, I'll cover four common strategies you can choose from. First, let's restate your class definitions for clarity:

public class ParameterDetails 
{ 
    public string Name { get; set; } 
    public List<Parameter> Parameters { get; set; } = new List<Parameter>(); 
} 

public class Parameter 
{ 
    public string Name { get; set; } 
    public string Type { get; set; } 
    public string Value { get; set; } 
    public string AccountName { get; set; } 
}

Strategy 1: Keep the First Occurrence of Each Parameter Name

Retain the first instance of a Parameter with a given Name and discard all subsequent duplicates:

public static List<ParameterDetails> RemoveDuplicatesKeepFirst(List<ParameterDetails> inputList)
{
    foreach (var details in inputList)
    {
        var seenNames = new HashSet<string>();
        details.Parameters = details.Parameters
            .Where(param => seenNames.Add(param.Name))
            .ToList();
    }
    return inputList;
}

Strategy 2: Keep the Last Occurrence of Each Parameter Name

Preserve the most recent (last) instance of a duplicate Parameter:

public static List<ParameterDetails> RemoveDuplicatesKeepLast(List<ParameterDetails> inputList)
{
    foreach (var details in inputList)
    {
        var seenNames = new HashSet<string>();
        details.Parameters = details.Parameters
            .Reverse()
            .Where(param => seenNames.Add(param.Name))
            .Reverse()
            .ToList();
    }
    return inputList;
}

Strategy 3: Merge Duplicate Parameters

Combine values from duplicates (e.g., concatenate Value or AccountName fields) into a single Parameter:

public static List<ParameterDetails> MergeDuplicateParameters(List<ParameterDetails> inputList)
{
    foreach (var details in inputList)
    {
        details.Parameters = details.Parameters
            .GroupBy(param => param.Name)
            .Select(group => new Parameter
            {
                Name = group.Key,
                Type = group.First().Type, // Assume Type is consistent for duplicates
                Value = string.Join("; ", group.Select(p => p.Value)),
                AccountName = string.Join("; ", group.Select(p => p.AccountName))
            })
            .ToList();
    }
    return inputList;
}

Strategy 4: Throw an Exception for Duplicates

If duplicates are invalid and should trigger an error:

public static List<ParameterDetails> ValidateUniqueParameters(List<ParameterDetails> inputList)
{
    foreach (var details in inputList)
    {
        var seenNames = new HashSet<string>();
        foreach (var param in details.Parameters)
        {
            if (!seenNames.Add(param.Name))
            {
                throw new InvalidOperationException(
                    $"Duplicate Parameter name '{param.Name}' found in ParameterDetails '{details.Name}'.");
            }
        }
    }
    return inputList;
}

Bonus: Case-Insensitive Comparison

To treat "Param1" and "param1" as duplicates, modify the HashSet to use a case-insensitive comparer:

var seenNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

内容的提问来源于stack exchange,提问作者Rohi_Dev_1.0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:45:52