如何添加更新删除重复的键值对列表



我需要一个通用方法才能从重复键值对列表中添加更新删除

我的重复键值对看起来像这个

List<KeyValuePair<string, int>> dupesStudentIdsList = new List<KeyValuePair<string, int>>();
dupesStudentIdsList.Add(new KeyValuePair<string, int>("1234_456X", 1));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("1234_456X", 2));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("1234_456X", 3));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("1234_456X", 4));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("1234_456X", 5));
//new set of duplicate ids with increasing rowNumber 
dupesStudentIdsList.Add(new KeyValuePair<string, int>("9999_999A", 1));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("9999_999A", 2));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("9999_999A", 4));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("9999_999A", 5));
dupesStudentIdsList.Add(new KeyValuePair<string, int>("9999_999A", 6));

我现在需要什么当我传递键时,它应该删除该键的所有行。

private void RemoveDupesbyKey(string DupeKey) //passing "1234_456X"
{
}   

//密钥作为"123_456X"传递时的预期结果

("9999_999A", 1));
("9999_999A", 2));
("9999_999A", 4));
("9999_999A", 5));
("9999_999A", 6));

现在我想通过传递Key和Value("9999_999A",6(只删除一条记录

private void RemoveByPassingKeyandValue(string key , int Value) // this is passed
{
}

//预期结果

("9999_999A", 1));
("9999_999A", 2));
("9999_999A", 4));
("9999_999A", 5));  // last row is removed. 

//仅更新通过密钥和值的值

private void updateValueOnly(string key , int Value) // Only Value update for the Key
{
}

//预期结果

("9999_999A", 1));
("9999_999A", 2));
("9999_999A", 4));
("9999_999A", 999999));  //only value is updated for that key and value 

这就是我所管理的。如果有更好的方法,我会很感激。

private void RemoveDupesbyKey(string DupeKey) //passing "1234_456X"
{
dupesStudentIdsList.RemoveAll(x => x.Key.Equals(Dupekey));
}
private void RemoveByPassingKeyandValue(string key, int Value) // this is passed
{
dupesStudentIdsList.Remove(new KeyValuePair<string, int>(key, Value));
}

由于KeyValuePair是不可变的。我们需要删除并添加它。

private void UpdateValueOnly(string key, int Value) // this is passed
{
if (dupesStudentIdList.Where(x => x.Key.Equals(key) && x.Value.Equals(Value).Any()))//check if it matches 
{
//remove
dupesStudentIdsList.Remove(new KeyValuePair<string, int>(key, Value));
// add 
dupesStudentIdsList.Add(new KeyValuePair<string, int>(key, Value));
}
}

最新更新