【发布时间】:2020-06-12 17:54:49
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp5
{
class Validator
{
static void Main()
{
var metaValues = new List<Meta>
{
new Meta(4, 15, true),
new Meta(5, 20, false)
};
var requestDict = new Dictionary<int, List<int>>
{
{4, new List<int>{15,20} },// error not exist
{5, new List<int>{25} }, // error its false
{6, new List<int>{30} } // error not exist
};
var matchedIds = new List<int>();
if (metaValues.Any())
{
foreach (var ob in metaValues)
{
if (requestDict.ContainsKey(ob.Id))
{
matchedIds.Add(ob.Id);
var valuesDict = requestDict[ob.Id];
//here i cant get all the values and its Active of meta.Id
}
}
}
foreach (var key in requestDict.Keys)
{
if (!matchedIds.Contains(key))
Console.WriteLine("Invalid");
}
}
}
public class Meta
{
public int Id { get; private set; }
public int Value { get; private set; }
public bool IsActive { get; private set; }
public Meta(int id, int value, bool isActive)
{
Id = id;
Value = value;
IsActive = isActive;
}
}
}
使用对象迭代字典会导致性能问题,因为每次字典键都必须在对象列表中进行迭代,所以我试图在以下条件下获取对象并在字典中查找
- 字典键中不存在 meta.Id 时无效
- 当 meta.Value 之一在字典值列表中不存在时无效
- 当 meta.Id 和 meta.value 与字典匹配但 meta.isactive 为 false 时无效
【问题讨论】:
-
请修正缩进,这样就没有那么多水平滚动了!
-
为什么要创建一个与内置类型同名的类?它增加了不必要的混乱(在我看来,无论如何)。
-
发布的代码不会编译。请使用实际代码更新问题。
-
“对象属性”是什么意思?请解释您的代码的目的,即。你想做什么。
-
请注意,
object和Object在上面的代码中是不同的。
标签: c# dictionary object