c# 列表中<>选择特定变量

本文关键字:变量 选择 列表 | 更新日期: 2023-09-27 18:31:32

我有网格视图(ASPxGridView),我想填充行。我的 c# 代码是这样的:

List<ProductEntity> productList;
productList = product.getProducts();
gvProducts.DataSource =...
gvProducts.DataBind();

我不想显示产品实体的所有变量,只显示名称和价格。

我知道有很多方法,但什么是最简单,最简单的方法?

我尝试了这样的事情:

productList = product.getProducts().foreach()

但它没有用。谢谢。

c# 列表中<>选择特定变量

没有看到更多代码,我不能肯定地说,但如果您只想从产品中选择名称和价格......

List<ProductEntity> productList;
productList = product.getProducts()
                       .Select(p => new {  p.Name, p.Price });

编辑:扩展我的代码示例以显示工作测试:

 using System.Collections.Generic;
    using System.Linq;
    using NUnit.Framework;
    namespace StackOverflow
    {
        [TestFixture]
        public class ProductListQuestion
        {
            class ProductEntity
            {
                public string Name { get; set; }
                public decimal Price { get; set; }
                public string OtherProperty { get; set; }
            }
            [Test]
            public void CanSelectProperties()
            {
                var products = new List<ProductEntity>
                {
                    new ProductEntity {Name = "First", Price = 1M},
                    new ProductEntity {Name = "Second", Price = 2M},
                    new ProductEntity {Name = "Third", Price = 3M}
                };
                var productList = products
                   .Select(p => new {  p.Name, p.Price });
                Assert.That(productList, Is.Not.Null);
                Assert.That(productList.Count(), Is.EqualTo(3));
                Assert.That(productList.ElementAt(0), Has.No.Property("OtherProperty"));
                Assert.That(productList.ElementAt(0), Has.Property("Name"));
            }
        }
    }
var result =product.getProducts().Select(x=> 
          new {Name = x.name ,
                  Price= x.price})
         .ToList();

在 GridView 上执行以下步骤:

  1. 禁用AutoGenerateColumns
  2. 点击网格视图比" Edit Columns "
  3. 添加要从实体中显示的列,例如,添加BoundField,它必须包含要显示HeaderText列的名称,以及实体中变量DataField名称