[英]How to use Linq in C# to do this?
I have this Object:我有这个 Object:
class Car
{
public int Id { get; set; }
public string Name { get; set; }
public Color Color { get; set; }
}
public enum Color
{
Red = 1,
Blue = 2,
Pink = 3,
Orange = 4,
}
How to create a linq query if I want take objects which have Red and Blue values:如果我想获取具有红色和蓝色值的对象,如何创建 linq 查询:
query = query.Where(at => at.Color == Color.Red + Color.Blue);
If I take you at face value, and you want cars to be able to have more than one colour then you need to change your enum
to use the Flags
attribute.如果我相信你的表面价值,并且你希望汽车能够拥有不止一种颜色,那么你需要更改你的
enum
以使用Flags
属性。
Like this:像这样:
[Flags]
public enum Color
{
Red = 1,
Blue = 2,
Pink = 4,
Orange = 8,
}
Now I can write this code:现在我可以写这段代码了:
var cars = new []
{
new Car() { Name = "Red & Orange", Color = Color.Red | Color.Orange },
new Car() { Name = "Red & Blue", Color = Color.Red | Color.Blue },
};
var query = cars.Where(at => at.Color == (Color.Red | Color.Blue));
That, indeed, returns just the "Red & Blue"
car.实际上,这只会返回
"Red & Blue"
汽车。
However, if you meant or rather than and then you don't need to change your enum
and the following is what you need:但是,如果您的意思是或而不是然后您不需要更改您的
enum
并且以下是您需要的:
query = query.Where(at => at.Color == Color.Red || at.Color == Color.Blue);
Either you can make the query with ||
您可以使用
||
进行查询or operator或操作员
query = query.Where(at => at.Color == Color.Red
|| at.Color == Color.Blue);
Or create an Color
array to check whether the value is within the array.或者创建一个
Color
数组来检查值是否在数组内。
query = query.Where(at => (new Color[] { Color.Red, Color.Blue }).Contains(at.Color));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.