[英]Count the items of a List according to their status
My question is simple, but I can't find a solution in my search. 我的问题很简单,但是在搜索中找不到解决方案。
Well, I have here these Classes and Lists: 好吧,我这里有这些类和列表:
public class Table
{
public string TableName { get; set; }
public string Status { get; set; }
public List<Request> Requests { get; set; }
}
public class Request
{
public string ProductName { get; set; }
public double ProductPrice { get; set; }
public int Quantity { get; set; }
}
public List<Table> Tables = new List<Table>();
The tables can have two status: Unoccupied
and Occupied
. 这些表可以具有两种状态: Unoccupied
和已Occupied
。 What I need is to count all the tables presents in the Table List and separate them according to Status, but I don't know how to do this. 我需要计算表列表中的所有表并根据状态将它们分开,但是我不知道该怎么做。 For example, I have two tables with their status occupied and three tables with their status unoccupied. 例如,我有两个表,它们的状态为已占用,三个表,它们的状态为未占用。 I need the output like: You have 2 tables occupied and 3 tables unoccupied
. 我需要这样的输出: You have 2 tables occupied and 3 tables unoccupied
。 I think I need to use a while
loop, but I don't know how to count separate. 我想我需要使用while
循环,但是我不知道如何分开计算。
Just use GroupBy
只需使用GroupBy
var results = Tables.GroupBy(t => t.Status)
.Select(g => new
{
Status = g.Key,
Count = g.Count()
});
foreach(var item in results)
{
Console.WriteLine("You have {0} tables of status {1}", item.Count, item.Status);
}
Note that this will only give you statuses that have at least one table, so if a status has none and you need that as well you can adjust to the following. 请注意,这只会为您提供至少包含一个表的状态,因此,如果一个状态不包含任何表,并且您也需要它,则可以调整以下内容。
var results = Tables.GroupBy(t => t.Status)
.ToDictionary(g => g.Key, g => g.Count());
foreach(var status in new[] {"Unoccupied", "Occupied"})
{
int count;
results.TryGetValue(status, out count);
Console.WriteLine("You have {0} tables of status {1}", count, status);
}
Also you might want to consider creating an enum
for the Status
if it should only be one of two values. 另外,如果Status
应该仅是两个值之一,则可能要考虑为其创建一个enum
。
public enum TableStatus
{
Unoccupied,
Occupied
}
You can use LINQ like: 您可以像这样使用LINQ:
List<Table> UnoccupiedTables = Tables.Where(r=> r.Status == "Unoccupied")
.ToList();
List<Table> OccupiedTables = Tables.Where(r=> r.Status == "Occupied")
.ToList();
If you want case insensitive comparison then you can replace you can use String.Equals
like: 如果要进行不区分大小写的比较,则可以替换为String.Equals
:
String.Equals(r.Status, "Occupied", StringComparison.InvariantCultureIgnoreCase)
I missed the part of getting count . 我错过了增加计数的部分。 You can use GroupBy
as mentioned in the other answer, or you can get count for each item like: 您可以使用另一个答案中提到的GroupBy
,也可以为每个项目计数,例如:
int CountOfUnoccupiedTables = Tables.Count(r=> r.Status == "Unoccupied");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.