我有一个包含 3 个项目的列表,两个 type_1 和一个 type_2。我想返回第二个列表,其中包含存在的该类型的类型和编号。当单步执行在 foreach 循环中设置的断点时,IF 语句永远不会为真。我认为我尝试使用 Contains() 方法有问题。
输出应该是这样的:
type_1 2
type_2 1
相反,它评估为:
type_1 1
type_1 1
type_2 1
我对 Contains() 的使用不正确吗?
public List<item_count> QueryGraphListingsNewAccountReport()
List<item> result = new List<items>();
var type_item1 = new item { account_type = "Type_1" };
var type_item2 = new item { account_type = "Type_1" };
var type_item3 = new item { account_type = "Type_2" };
result.Add(type_item1);
result.Add(type_item2);
result.Add(type_item3);
//Create a empty list that will hold the account_type AND a count of how many of that type exists:
List<item_count> result_count = new List<item_count>();
foreach (var item in result)
{
if (result_count.Contains(new item_count { account_type = item.account_type, count = 1 } ) == true)
{
var result_item = result_count.Find(x => x.account_type == item.account_type);
result_item.count += 1;
result_count.Add(result_item);
}
else
{
var result_item = new item_count { account_type = item.account_type, count = 1 };
result_count.Add(result_item);
}
}
return result_count;
}
public class item
{
public string account_type { get; set; }
}
public class item_count
{
public int count {get; set;}
public string account_type { get; set; }
}