我想从带有列表的表中选择许多值。
我有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
= 1
,2
和3
。
如何在C#中使用Linq实现此目的?我只需要按Texture
和Year
这是我尝试过的方法,但是我不确定如何从具有多个值的列表中进行选择(selectedItems
是一个列表,但我不知道如何查询多个列):
db.FabricTable.Select(o => o.Texture == selectedItems.Texture && o.Year == selectItems.Year)
答案 0 :(得分:2)
使用selectedItems.Texture
时会出现编译器错误,因为selectedItem
是一个包含具有Texture
属性的对象的列表。在FabricTable
中搜索所需项目时,您需要检查列表中的所有项目:
var items = db.FabricTable.Where(o => selectedItems.Any(selectedItem => o.Texture == selectedItem.Texture && o.Year == selectedItem.Year));
答案 1 :(得分:0)
尝试以下操作:
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; }
}
}