LINQ查询未返回预期结果

时间:2017-10-06 05:13:05

标签: c# linq

任何人都可以帮忙解决这个问题,我尝试使用LINQ执行一个简单的查询,但我没有得到预期的结果。

private void ButtonProductSearch_Click(object sender, EventArgs e)
{
    string userSearch = textBoxSearchText.Text.ToLower();

    var productSearch =
        from product in sales
        where product.ToString().ToLower() == userSearch
        select product;

    MessageBox.Show(productSearch.Count().ToString()); //For Testing

    sales.Clear();
    sales.AddRange(productSearch);
    DisplaySales(sales);
}

仅用于测试的消息返回0,我已确保输入相关的搜索字符串。

sales是一个Sale对象,它是从csv文件填充的,并且有一个dataGridView,它是从Sale对象填充的,截图如下。当应用程序运行时,销售人员从csv读取每一行,datagridview填充该数据,截图如下

screenshot

2 个答案:

答案 0 :(得分:2)

您需要了解在查询from product in sales中,product指的是sales,而不是名为Product的列。因此,在ToString()上执行product将返回该行的字符串表示形式(通常是类本身的名称)。您应该像这样编写查询:

var productSearch =
    from s in sales
    where s.Product.ToLower() == userSearch
    select product;

再次,s指的是销售的,因此拥有产品,价格和付款类型等所有属性。因此,您可以要求LINQ过滤行他们的Product属性等于userSearch。由于Product的类型为字符串,因此您甚至不需要对其进行ToString()

答案 1 :(得分:0)

我认为@dotNET的答案对我来说似乎是正确的答案。为了完整起见,我构建了一个示例,并且还实现了不区分大小写的搜索:

using System;
using System.Linq;
using Bogus;

public class Program
{
    public static void Main()
    {
        var productsFactory = new Faker<Product>()
            .StrictMode(true)
            .RuleFor(p => p.TransactionDate, f => f.Date.Between(DateTime.UtcNow.AddDays(-100), DateTime.UtcNow))
            .RuleFor(p => p.Category, f => f.Commerce.ProductAdjective())
            .RuleFor(p => p.Price, f => f.Random.Decimal(10, 100))
            .RuleFor(p => p.PaymentType, f => f.PickRandomWithout(PaymentType.Unknown))
            .RuleFor(p => p.Name, f => f.Commerce.ProductName())
            .RuleFor(p => p.City, f => f.Address.City())
            .RuleFor(p => p.State, f => f.Address.State())
            .RuleFor(p => p.Country, f => f.Address.Country());

        var products = productsFactory.Generate(50);
        var userSearch = products.Skip(3).First().Name.Substring(2, 3);
        var productSearch = products.Where(product => product.Name.IndexOf(userSearch, StringComparison.CurrentCultureIgnoreCase) >= 0);

        foreach (var result in productSearch)
        {
            Console.WriteLine(String.Format("{0:G} {1} {2:N2}", result.TransactionDate, result.Name, result.Price));
        }

        Console.ReadKey();
    }
}

public class Product
{
    public DateTime TransactionDate { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public PaymentType PaymentType { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

}

public enum PaymentType
{
    Unknown,
    Mastercard,
    Visa,
    Amex,
}