[英]linq how to build a where predicate
我想查詢形狀的IEnumerable。 我有不同種類的形狀,根據形狀的類型,它們以不同的方式與給定的坐標相關。
對於任何給定的坐標,我想找到它的相關形狀。 我想用Linq做到這一點。 但是由於缺乏了解而陷入困境。 搜索和閱讀已經花費了幾個小時,但是我可以找到正確的單詞來舉例說明我正在嘗試做的事情。 下面是一些代碼,希望能顯示我想做的概念,但顯然行不通。 必須有一種鏈接這些表達式的方法-我已經看過謂詞生成器並且可以使用它,但是我想首先學習更多基礎知識。 我該如何工作?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LinqLearning
{
public class Coordinate
{
public double X { get; set; }
public double Y { get; set; }
}
public abstract class Bounded
{
public Coordinate TopRight { get; set; }
public Coordinate BottomLeft { get; set; }
}
public class Shape1 : Bounded
{ }
public class Shape2 : Bounded
{ }
public class LinqExperiments
{
public IEnumerable<Bounded> GetSquaresNearPoint(IEnumerable<Bounded> shapesEnumerable, Coordinate locator)
{
Expression<Func<Bounded, Coordinate, bool>> Shape1NearCoordinate =
(shape, coord) => shape.TopRight.Y > coord.Y &&
shape.BottomLeft.Y < coord.Y &&
shape.TopRight.X == coord.X;
Expression<Func<Bounded, Coordinate, bool>> Shape2NearCoordinate =
(shape, coord) => shape.TopRight.Y == coord.Y &&
shape.TopRight.X < coord.X + 3 &&
shape.TopRight.X > coord.X - 3;
Expression<Func<IQueryable<Bounded>, Coordinate, bool>> predicate = (shapes, coord) => Shape1NearCoordinate || Shape2NearCoordinate;
return shapesEnumerable.AsQueryable().Where(predicate);
}
}
}
我真的不明白為什么要使用Expression
和IQueryable
。 我認為這可以通過Func<Bounded, Coordinate, bool>
來解決:
public IEnumerable<Bounded> GetSquaresNearPoint(IEnumerable<Bounded> shapesEnumerable, Coordinate locator)
{
Func<Bounded, Coordinate, bool> Shape1NearCoordinate =
(shape, coord) => shape.TopRight.Y > coord.Y &&
shape.BottomLeft.Y < coord.Y &&
shape.TopRight.X == coord.X;
Func<Bounded, Coordinate, bool> Shape2NearCoordinate =
(shape, coord) => shape.TopRight.Y == coord.Y &&
shape.TopRight.X < coord.X + 3 &&
shape.TopRight.X > coord.X - 3;
Func<Bounded, Coordinate, bool> predicate = (shapes, coord) => Shape1NearCoordinate(shapes, coord) || Shape2NearCoordinate(shapes, coord);
return shapesEnumerable.Where(x => predicate(x, locator));
}
為什么不堅持簡單的簡單功能呢? 當真正不需要Lambda
或Linq Expressions
時,無需使用它們。
static bool Shape1NearCoordinate(Bounded shape, Coordinate coord) {
return shape.TopRight.Y > coord.Y &&
shape.BottomLeft.Y < coord.Y &&
shape.TopRight.X == coord.X;
}
static bool Shape2NearCoordinate(Bounded shape, Coordinate coord) {
return shape.TopRight.Y == coord.Y &&
shape.TopRight.X < coord.X + 3 &&
shape.TopRight.X > coord.X - 3;
}
public IEnumerable<Bounded> GetSquaresNearPoint(IEnumerable<Bounded> shapesEnumerable, Coordinate locator) {
return shapesEnumerable.Where(shape => Shape1NearCoordinate(shape, locator) || Shape2NearCoordinate(shape, locator));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.