0

私は顧客のリストを持っています:

List<customer> customerList;

Country="India" および Status="A" を持つ顧客だけを取得したいと考えています。

私はこれを試しました:

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India") && p.Status.Equals("A")).ToList();

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India")).Where(p=>p.Status.Equals("A")).ToList();

しかし、どちらも何も返しませんでした。

以下の例のように条件を分割すると、レコードは正しく取得されています。

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India")).ToList();
customerList=customerList.Where(p=>p.Status.Equals("A")).ToList();

単一のクエリで AND 条件を使用してオブジェクトをフィルター処理する方法を知りたいです。

誰でも言うことができますか、どこの条件を呼び出すよりも良い方法はありますか

4

2 に答える 2

3

この場合は使用しないでください.Equals。等価演算子 (==) を使用します。

customerList.Where(p=>p.Country == "India" && p.Status == "A").ToList();

Jon Skeet の記事 - == を使用する必要がある場合と Equals を使用する必要がある場合は?

値型の場合、コードを読みやすくするために通常は == を使用します。値型が Equals とは異なる動作をする == のオーバーロードを提供する場合、事態はややこしくなりますが、そのような型は最初から設計が非常に悪いと考えています。

ただし、リストが実際に入力されていることを確認する必要があります。

于 2012-10-11T14:02:46.317 に答える
0

これは期待どおりに機能するため、何をしていたかはわかりませんが、元のアプローチは正しかったです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4 {
    public class Customer {
        public string Country { get; set; }
        public string Status { get; set; }
    }

    class Program {
        static void Main(string[] args) {
            var list = new List<Customer>();
            list.Add(new Customer() { Country = "India", Status = "A" });
            list.Add(new Customer() { Country = "USA", Status = "A" });

            var results = list.Where((c) => c.Country == "India" && c.Status == "A");

            if (results.Any()) {
                Console.WriteLine(results.First().Country);
            }

            Console.ReadLine();
        }
    }
}
于 2012-10-11T14:06:45.153 に答える