我有課:
public class Class1
{
public int Id { get; set; }
public double MyDouble { get; set; }
public string SomeOtherValue { get; set; }
}
我有兩個字典<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 });
我想通過 blankValue 字典和 currentValue 中的每個元素,其中 blankValue.Value.ID == currentValue.Value.Id 我想設定 blankValue.Value.MyDouble = currentValue.Value.MyDouble。
blankValues 字典中的最終結果將導致:
Class1() { Id = 1, MyDouble = 0 });
Class1() { Id = 2, MyDouble = 3.1414927 });
Class1() { Id = 3, MyDouble = 0 });
就像我需要一個嵌套的 Linq。我會把我嘗試過的東西放在這里,但我所做的每一次嘗試甚至都沒有接近編譯。像這樣的 Linq 通常會是什么樣子?
編輯- 我應該補充說這個類有兩個以上的值。我想將所有屬性值保留在 blankValues 字典中,除了一兩個。
uj5u.com熱心網友回復:
GroupJoindocs:如果inner的給定元素中沒有相關元素outer,則該元素的匹配序列將為空,但仍會出現在結果中。
我假設 ID 在每本詞典中都是唯一的。
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)
uj5u.com熱心網友回復:
我想你想通過 dictionary.Key 而不是 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);
}
或者,如果你真的需要通過 id 檢查它看起來像這樣:
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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324908.html
上一篇:如何使用linq更新多行資料?
