我正在尝试删除字典第三级中的信息,并且只能在删除此信息后使用它。 但我不能,我做错了什么?
public class Person
{
int id;
string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int ID
{
get { return id; }
set { id = value; }
}
public List<Product> ListProd;
}
public class Product
{
public int idProd;
public string Description;
public List<Tax> listTax;
}
public class Tax
{
public int idTax;
public string Value;
}
//Method
public void SomeMethod()
{
Dictionary<int, List<int>> dicRemove = new Dictionary<int, List<int>>();
List<int> listTaxToRemove = new List<int>();
for (int m = 8; m < 10; m++)
{
listTaxToRemove.Add(m);
}
dicRemove.Add(10, listTaxToRemove);
Dictionary<int, List<Person>> dic = new Dictionary<int, List<Person>>();
List<Person> list = new List<Person>();
for (int i = 0; i < 2; i++)
{
Person d = new Person();
d.ID = i;
d.Name = "Person " + i;
d.ListProd = new List<Product>();
for (int j = 3; j < 6; j++)
{
Product p = new Product();
p.idProd = j;
p.Description = "Product " + j;
d.ListProd.Add(p);
p.listTax = new List<Tax>();
for (int m = 7; m < 10; m++)
{
Tax t = new Tax();
t.idTax = m;
t.Value = "Tax " + m;
p.listTax.Add(t);
}
}
list.Add(d);
}
dic.Add(10, list);
var q = dic.Select(s => s.Value
.Select(s1 => s1.ListProd
.Select(s2 => s2.listTax
.RemoveAll(r =>!dicRemove[s.Key].Contains(r.idTax))))).ToList();
}
我尝试了很多方法,通过迭代,这种方法只是删除了不必要的记录。
谢谢!
答案 0 :(得分:0)
RemoveAll
的延迟执行,未调用 Select
您有3个Select
,只有一个ToList()
q
的类型为System.Collections.Generic.List'1[System.Collections.Generic.IEnumerable'1[System.Collections.Generic.IEnumerable'1[System.Int32]]]
存在未枚举的嵌套IEnumerable
对象
这是一个工作变量但绝对不可读,不要这样做
var q = dic.Select(s => s.Value.Select(s1 => s1.ListProd.Select(s2 => s2.listTax.RemoveAll(r=>!dicRemove[s.Key].Contains(r.idTax)))
.ToList())
.ToList())
.ToList();
改进的变体
foreach(var pair in dic)
foreach(var person in pair.Value)
foreach(var prod in person.ListProd)
prod.listTax.RemoveAll(t=>!dicRemove[pair.Key].Contains(t.idTax));