在 sql List<int> 中搜索?

时间:2020-12-27 08:35:19

标签: linq

有一个 List 类型的数组。这个数组中有ID。我想用这些 ID 获取所有记录。我是这样做的。使用“For”,我总是在阵列中旋转时建立或连接。就像(id = 1 或 id = 2 或 ..)。有使用 linq 的快捷方式吗?谢谢。

2 个答案:

答案 0 :(得分:0)

有一个 Contains 方法。你有没有试过这个:

var listOfIds = new List<int> { 1, 23, 42 };

result = result.Where(r => listOfIds.Contains(r.ID)

答案 1 :(得分:0)

参见.net Fiddle https://dotnetfiddle.net/zLlNeb

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Collections;
                
 public class Program
 {
   public static void Main()
   {
    //if  you want from  list of strings
    var listOfIds = new List<int> { 1, 23, 42 };
    int id  = 23;
    var result = listOfIds.AsEnumerable().Where(r => r == id).ToList();
    Console.WriteLine(string.Join(",", result));

//----------------------------------------- ------------------------

    // if you want from a list of objects
           List<Customer>  custList  = new List<Customer>();
    custList.Add(new Customer("IBM","1001","19056"));
    custList.Add(new Customer("IBM","1001","19056"));
    custList.Add(new Customer("Microsoft","2002","65009"));
    custList.Add(new Customer("Oracle","3003","5211"));
    
     string custId  = "1001";
    var result2 = custList.Where(r => r.Id == custId).ToList();
    foreach(Customer c  in result2)
    {
        Console.WriteLine(string.Concat(c.Id,",",c.Name,",",c.Zip) );
    }
}

}

   public class Customer
   {
    public string Name {get; set;}
    public string Id {get; set;}
    public string Zip {get; set;}

    public Customer(string name,string id, string zip)
    {
    this.Name = name;
    this.Id  = id;
    this.Zip  = zip;
}

}

相关问题