C# 是否有一种方法可以从具有特定属性的列表中获取所有项目
我有一个容器列表,想知道如何返回一个包含所有有价值容器的列表 这是我目前的代码: ContainerType.cs:C# 是否有一种方法可以从具有特定属性的列表中获取所有项目,c#,linq,enums,C#,Linq,Enums,我有一个容器列表,想知道如何返回一个包含所有有价值容器的列表 这是我目前的代码: ContainerType.cs: public enum ContainerType { Normal, Cooled, Valuable } Container.cs: public ContainerType Type; public int Weight { set; get; } p
public enum ContainerType
{
Normal,
Cooled,
Valuable
}
Container.cs:
public ContainerType Type;
public int Weight { set; get; }
public Container(ContainerType type, int weight)
{
Weight = weight;
Type = type;
}
Row.cs:
public List<Container> GetValuable(List<Container> List)
{
return List.OfType<ContainerType.Valuable>();
}
public List getvalue(列表)
{
返回List.OfType();
}
第行中的方法给出了以下两个错误:
CS0426 The type name 'Valuable' does not exist in the type 'ContainerType'
CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Containervervoer.Models.ContainerType.Valuable>' to 'System.Collections.Generic.List<Containervervoer.Models.Container>'. An explicit conversion exists (are you missing a cast?)
CS0426类型“ContainerType”中不存在类型名称“valuel”
CS0266无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(是否缺少强制转换?)
您可以使用LINQWhere
功能来实现这一点
public List<Container> GetValuable(List<Container> list)
{
return list.Where(x => x.ContainerType == ContainerType.Valuable).ToList();
}
public List getvalue(列表)
{
return list.Where(x=>x.ContainerType==ContainerType.valuely.ToList();
}
ToList()
应该可以解决您的铸造问题。您可能会对其工作原理或功能感到困惑。一个简单的Where
应该有效你是对的,samyap的回答是有效的。没问题,请阅读本文以获得有关Where
如何工作的更多信息: