繁体   English   中英

C#LINQ从具有多个字段的列表中选择表

[英]C# LINQ Select table from list with multiple fields

我想从带有列表的表中选择许多值。 我有FabricTable (年份为int ):

+----+-------+---------+------+
| Id | Color | Texture | Year |
+----+-------+---------+------+
| 1  | Red   | Rough   | 2019 |
+----+-------+---------+------+
| 2  | Green | Soft    | 2019 |
+----+-------+---------+------+
| 3  | Blue  | Rough   | 2019 |
+----+-------+---------+------+
| 4  | Red   | Med     | 2019 |
+----+-------+---------+------+
| 5  | Blue  | Soft    | 2018 |
+----+-------+---------+------+

我已经selectedItems列表(年份是int ):

+---------+------+
| Texture | Year |
+---------+------+
| Rough   | 2019 |
+---------+------+
| Soft    | 2019 |
+---------+------+

我想获得的Id从表中,它应该导致Id = 12 ,和3

如何在C#中使用Linq实现此目的? 我只需TextureYear选择

这是我尝试过的方法,但是我不确定如何从具有多个值的列表中selectedItemsselectedItems是一个列表,但是我不知道如何查询多个列):

db.FabricTable.Select(o => o.Texture == selectedItems.Texture && o.Year == selectItems.Year)

使用selectedItems.Texture时会出现编译器错误,因为selectedItem是一个包含具有Texture属性的对象的列表。 FabricTable搜索所需项目时,需要检查列表中的所有项目:

var items = db.FabricTable.Where(o => selectedItems.Any(selectedItem => o.Texture == selectedItem.Texture && o.Year == selectedItem.Year));

尝试以下操作:

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


namespace ConsoleApplication120
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Item> items = new List<Item>() { 
                new Item() { Id = 1, Color = "Red", Texture = "Rough",  Year = 2019},
                new Item() { Id = 2, Color = "Green", Texture = "Soft",  Year = 2019},
                new Item() { Id = 3, Color = "Blue", Texture = "Rough",  Year = 2019},
                new Item() { Id = 4, Color = "Red", Texture = "Soft",  Year = 2018}
            };
            DataTable dt = new DataTable();
            dt.Columns.Add("Color", typeof(string));
            dt.Columns.Add("Texture", typeof(string));
            dt.Columns.Add("Year", typeof(int));

            foreach (Item item in items.Where(x => (x.Texture == "Rough") && (x.Year == 2019)))
            {
                dt.Rows.Add(new object[] { item.Color, item.Texture, item.Year });
            }

        }

    }
    public class Item
    {
        public int Id { get; set; }
        public string Color { get; set; }
        public string Texture { get; set; }
        public int Year { get; set; }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM