Home > Blockchain >  Linq for updating property of A.property with matching B.property where A.Key == B.Key
Linq for updating property of A.property with matching B.property where A.Key == B.Key

Time:10-19

I have the class:

public class Class1
{
    public int Id { get; set; }
    public double MyDouble { get; set; }
    public string SomeOtherValue { get; set; }
}

And I have two dictionaries<int, Class1>:

Dictionary<int, Class1> blankValues = new Dictionary<int, Class1>();
blankValues.Add(1, new Class1() { Id = 1, MyDouble = 0 });
blankValues.Add(2, new Class1() { Id = 2, MyDouble = 0 });
blankValues.Add(3, new Class1() { Id = 3, MyDouble = 0 });

Dictionary<int, Class1> currentValues = new Dictionary<int, Class1>();
currentValues.Add(2, new Class1() { Id = 2, MyDouble = 3.1415927 });

I want to go through the blankValue dictionary and for every element in currentValue where blankValue.Value.ID == currentValue.Value.Id I want to set blankValue.Value.MyDouble = currentValue.Value.MyDouble.

The end result in blankValues dictionary would result in:

Class1() { Id = 1, MyDouble = 0 });
Class1() { Id = 2, MyDouble = 3.1414927 });
Class1() { Id = 3, MyDouble = 0 });

It's like I need a nested Linq. I would put what I have tried here but every attempt I make doesn't even come close to compiling. What would a Linq like this generally look like?

edit - I should add that the class has more than two values. I want to keep all the property values in blankValues dictionary except on or two.

CodePudding user response:

GroupJoin docs: If there are no correlated elements in inner for a given element of outer, the sequence of matches for that element will be empty but will still appear in the results.

I assume ID's are unique among every dictionary.

blankValues = blankValues.GroupJoin(
    currentValues,
    pair => pair.Value.Id,
    pair => pair.Value.Id,
    // Select rather blank values member or current values member
    (blankValue, matches) => matches.Any() ? matches.First() : blankValue))
.ToDictionary(x => x.Id, x => x)

CodePudding user response:

I think you want to check by dictionary.Key not dictionary.Value.Id:

foreach (var (key, value) in currentValues )
{
    if (blankValues.ContainsKey(key))
    {
        blankValues[key] = value;
        continue;
    }
    //remove line below if you don't need to add missing values in first list
    blankValues.Add(key, value);
}

Or if you really need to check by id it would look smth like this:

foreach (var (key, value) in currentValues)
{
    var blanks = blankValues
                 .Where(x => x.Value.Id == value.Id)
                 .ToList();
    foreach (var blank in blanks)
    {
        blankValues[blank.Key] = value;
    }
}
  • Related