1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# クエリ構文で複数項目の取得する時の書き方

Last updated at Posted at 2020-12-29

【結論】
クエリ構文で複数の項目を取得したい場合、
select A.Id,A.Name;
のように書くことはできず、
**new と{}**を記載して下記のように書く必要がある
select new { A.Id, A.Name };

※追記
 @albireoさんのコメントを本文に追記
 C#7.0以降だとnew を記載せずとも**()**で記載が可能になった。
select **(**A.Id, A.Name );

サンプルコード

        var products = new List<Product>();

        products.Add(new Product(10, "A", 200));
        products.Add(new Product(20, "B", 300));
        products.Add(new Product(30, "C", 400));
        products.Add(new Product(40, "D", 500));

        // selectしたい項目が1つの場合
        var result1 = from product in products
                     select product.ProductName;  

        foreach (var val in result1)
        {
            Console.WriteLine("select(取得したい項目1つ)"+ string.Join(",", val.ProductName));
        }


        // selectしたい項目が複数の場合 パターン1
        var result2 = from product in products
                     select new { product.ProductId, product.ProductName};  //★★★ポイント★★★

        // ※追記
        // selectしたい項目が複数の場合 パターン2
        var result2 = from product in products
                     select (product.ProductId, product.ProductName);  //★★★ポイント★★★

        foreach (var product in result2)
        {
            Console.WriteLine("select(取得したい項目複数)" + "ID:"+ product.ProductId + " Name:" + product.ProductName);
        }

select (product.ProductId, product.ProductName);

public sealed class Product 
{
    public Product(int producted, string productName, int price)
    {
        ProductId = producted;
        ProductName = productName;
        Price = price;
    }

    public int ProductId { get; }
    public string ProductName { get; }
    public int Price { get; }
}

おまけ

Select結果の名前を変更したい場合
Select文内で代入処理を行うことで実現できる

        var result2 = from product in products
                     select new { product.ProductId, ItemName = "商品名:" + product.ProductName}; //★★★ポイント★★★

        foreach (var product in result2)
        {
            Console.WriteLine("select(取得したい項目複数)" + "ID:"+ product.ProductId + " Name:" + product.ItemName);
        }
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?