[Linq] Linq 中使用 Select Where In List 條件

  • 16823
  • 0
  • Linq
  • 2018-05-30

常在寫SQL習慣了,應該很習慣以下語法

Select id from Product
Where type in ('PC', 'NB');

在Linq 中,沒這麼快快樂樂  XXX in (AAA, BBB) 的語法,必須要改用 Contains,
今天就遇到一個茶包問題,萬一我的產品有 PC, Dell_PC,用Contains 下去查 PC 的品項,Dell_PC也跑出來呢?

https://dotnetfiddle.net/BsNLvJ

用以下的小範例驗證,結果是一樣的,並無查詢 A,跑出 Acer, ASUS 的情形。

public static void Main()
{
	var list = new List<string>() {"ASUS_PC","Acer_PC","BenQ", "Toshiba","IBM","HP","Dell"}; 
	var ss = new List<string>() {"PC", "IBM", "Acer_PC", "A"};
	string s2 = "PC, IBM, Acer_PC, A";
	var r0 = list.Where(l => ss.Contains(l));
	var r1 = list.Where(l => s2.Contains(l));
	var r2 = list.Where(l => ss.Any(p => p.Equals(l)));
	
	Console.WriteLine("List Contains Case");
	foreach (var item in r0)
	{
	   Console.WriteLine(item);
	}
	Console.WriteLine();
	
	Console.WriteLine("String Contains Case");
	foreach (var item in r1)
	{
	   Console.WriteLine(item);
	}
	Console.WriteLine();
	
	Console.WriteLine("List equals Case");
	foreach (var item in r2)
	{
	   Console.WriteLine(item);
	}
	Console.WriteLine();
}
Result: 

List Contains Case
Acer_PC
IBM

String Contains Case
Acer_PC
IBM

List equals Case
Acer_PC
IBM

Ref.
https://stackoverflow.com/questions/1075540/linq-to-sql-how-to-do-where-column-in-list-of-values
https://stackoverflow.com/questions/1175645/find-an-item-in-list-by-linq