如何在C#中将if语句添加到LINQ查询?

时间:2015-04-23 11:06:25

标签: c# linq

考虑以下查询方法:

internal List<Product> productInStockQuery(InStock inStock1)
{
    var inStock =
        from p in products
        where p.INStock == inStock1
        select p;

    return inStock.ToList<Product>();
}

我希望该方法可以执行以下操作:

如果inStock1 == InStock.needToOrder我想要搜索两者(类似):     (instock1==InStock.needToOrder && instock1==InStock.False)

我该怎么做?

我还想知道是否可以创建一种方法,允许我在一个方法中搜索我的所有产品字段。

编辑部分 :(我提出的第二个问题) 试图更好地解释自己:我的类有几个字段,现在每个字段我有一个如上所示的方法我想知道是否有可能创建一个特殊的变量,允许我访问产品中的每个字段而不实际输入字段名称或getters而不是p.price / p.p​​roductName我只需输入p.VARIABLE并根据此变量我将访问想要的字段/ getter

如果存在这样的选项,如果您能告诉我在网上搜索什么,我将不胜感激。

P.S 非常感谢所有的快速反应,我正在检查它们。

4 个答案:

答案 0 :(得分:1)

你的意思是使用像Enum这样的东西吗?

internal enum InStock
{
    NeedToOrder,
    NotInStock,
    InStock
}

internal class Product
{
    public string Name { get; set; }
    public InStock Stock { get; set; }
}

然后将一个集合传递给方法......

  internal static List<Product> ProductInStockQuery(List<Product> products)
        {

            var inStock =
                from p in products
                where p.Stock != InStock.NeedToOrder && p.Stock != InStock.NotInStock
                select p;

            return inStock.ToList();
        }

创建一个列表并将其传递给...

        var prods = new List<Product>
        {
            new Product
            {
                Name = "Im in stock",
                Stock = InStock.InStock
            },
            new Product
            {
                Name = "Im in stock too",
                Stock = InStock.InStock
            },
            new Product
            {
                Name = "Im not in stock",
                Stock = InStock.NotInStock
            },
            new Product
            {
                Name = "need to order me",
                Stock = InStock.NotInStock
            },
        };


        var products = ProductInStockQuery(prods);

答案 1 :(得分:0)

您可以根据输入变量组合查询,如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
    locationManager.delegate = self; // we set the delegate of locationManager to self. 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy

    [locationManager startUpdatingLocation];  //requesting location updates
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"There was an error retrieving your location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorAlert show];
    NSLog(@"Error: %@",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *crnLoc = [locations lastObject];
    latitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.latitude];
    longitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.longitude];
    altitude.text = [NSString stringWithFormat:@"%.0f m",crnLoc.altitude];
    speed.text = [NSString stringWithFormat:@"%.1f m/s", crnLoc.speed];
}

答案 2 :(得分:0)

我相信您可以使用 WhereIf LINQ扩展方法使其更加清晰和可重用。以下是扩展程序的示例

public static class MyLinqExtensions
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, Boolean condition, System.Linq.Expressions.Expression<Func<T, Boolean>> predicate)
    {
        return condition ? source.Where(predicate) : source;
    }

    public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, Boolean condition, Func<T, Boolean> predicate)
    {
        return condition ? source.Where(predicate) : source;
    }
}

下面您可以看到如何使用此方法的示例

class Program
{
    static void Main(string[] args)
    {
        var array = new List<Int32>() { 1, 2, 3, 4 };
        var condition = false;                              // change it to see different outputs
        array
            .WhereIf<Int32>(condition, x => x % 2 == 0)     // predicate will be applied only if condition TRUE
            .WhereIf<Int32>(!condition, x => x % 3 == 0)    // predicate will be applied only if condition FALSE
            .ToList()                                       // don't call ToList() multiple times in the real world scenario
            .ForEach(x => Console.WriteLine(x));  

    }
}

答案 3 :(得分:-1)

q = (from p in products);
if (inStock1 == InStock.NeedToOrder)
    q = q.Where(p => p.INStock == InStock.False || p.InStock == InStock.needToOrder);
else
    q = q.Where(p => p.INStock == inStock1);

return q.ToList();