Home > Mobile >  How to merge to different object lists by key C#
How to merge to different object lists by key C#

Time:10-18

I've got two classes that I would like to merge/map by the Name property in each of them

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

public class RuleSetParameter
{
    public string ParameterName { get; set; }
    public string ParameterValue { get; set; }
    public int ParameterType { get; set; }
 }

I would like to merge these two lists, by joining them on the Name <-> ParameterName props, so that I can get the ParameterValue.

This is what I have thus far:

var parameterDictionary = RuleSetParameter.Zip(parameters).ToDictionary(x => x.First, x => x.Second);

I know this won't work, because this will just map them in the order received.

Any guidance on how to achieve the desired result?

CodePudding user response:

Managed to get this resolved using the Join method:

 var result = fieldMap.RuleSetParameter.Join(parameters, arg => arg.ParameterName, arg => arg.Name,
                (first, second) => new { first.ParameterName, ParameterValue = second.Value, first.ParameterType });

CodePudding user response:

I would define an interface

public interface IParameter
{
   string Name { get; set; }
   string Value { get; set; }
}

public class Parameter : IParameter
{
   public string Name { get; set; }
   public string Value { get; set; }
}

public class RuleSetParameter : IParameter
{
    public string ParameterName { get; set; }
    public string ParameterValue { get; set; }
    public int ParameterType { get; set; }

    //explicit interface implementation 
    string IParameter.Name 
    { 
        get => this.ParameterName;
        set => this.ParameterName = value;
    }
    string IParameter.Value
    { 
        get => this.ParameterValue;
        set => this.ParameterValue = value;
    }
}

Now you can easily define a IDictionary<string, IParameter>

var parameters = new List<Parameter>()
{
    new() { Name = "P1", Value = "V1" },
    new() { Name = "P2", Value = "V2" },
};

var resultSetParameters = new List<RuleSetParameter>()
{
    new() { ParameterName = "RP1", ParameterValue = "RV1" },
    new() { ParameterName = "RP2", ParameterValue = "RV2" },
};

var dictParametrs = parameters.Cast<IParameter>().Concat(resultSetParameters).ToDictionary(x => x.Name);

Here a demo:

sharplab.io

  • Related