LINQを使用して汎用リストからカスタムオブジェクトを取得する方法は?

StackOverflow https://stackoverflow.com/questions/618190

  •  03-07-2019
  •  | 
  •  

質問

次のコードで次のエラーが発生する理由

カスタムオブジェクトをそのタイプの汎用リストに入れると、IEnumerableが処理されると思いましたか? LINQを使用するには、このリストに対して他に何をする必要がありますか?

  

暗黙的に型を変換することはできません   'System.Collections.Generic.IEnumerable <TestLinq23.Customer>'   「TestLinq23.Customer」へ

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

namespace TestLinq23
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customerSet = new List<Customer>();
            customerSet.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" });
            customerSet.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" });
            customerSet.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" });

            Customer customerWithIndex = customerSet[1];
            Console.WriteLine("Customer last name gotten with index: {0}", customerWithIndex.LastName);

            Customer customerWithLinq = from c in customerSet
                           where c.FirstName == "Joe"
                           select c;
            Console.WriteLine(customerWithLinq.LastName);

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

}
役に立ちましたか?

解決

<=への呼び出しを追加する必要があります> -それ以外の場合は、顧客のシーケンスを返します。

同時に、ここでクエリ式を使用する必要はありません。ドット表記を使用する方が簡単です:

Customer customerWithLinq = customerSet.Where(c => c.FirstName == "Joe")
                                       .Single();

実際には、述語を取るためのSingle()のオーバーロードがあるため、さらに簡単にすることができます。

Customer customerWithLinq = customerSet.Single(c => c.FirstName == "Joe")

一致するものが1つだけではない場合、エラー状態ですか?そうでない場合は、 First() の代わりにSingleOrDefault()

編集:Garryが指摘したように、結果がないの場合、 FirstOrDefault() または null -一致するエントリがない場合、これらは両方とも<=>を返します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top