LINQ从List <list <string>&gt;获取List <string>任何</list <string> </string>

时间:2013-10-04 10:55:05

标签: c# linq list

使用LINQ,如何检索与其他列表匹配的项目列表列表?

示例:

List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();

dataSearch.Add("01");
dataSearch.Add("02");

data.Add("01");
data.Add("Book");
data.Add("9");
datas.Add(data);

data = new List<string>();
data.Add("02");
data.Add("Pen");
data.Add("2");
datas.Add(data);

data = new List<string>();
data.Add("03");
data.Add("Pencil");
data.Add("5");
datas.Add(data);

List<List<string>>中的预期结果:

List<string> ("01", "Book", "9")
List<string> ("02", "Pen", "2")

我试试

var result = datas.Where(x => x[0].Contains(dataSearch)).ToList();

我在编辑中得到了红色下划线。

2 个答案:

答案 0 :(得分:3)

这就是你要找的东西:

List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();

dataSearch.Add("01");
dataSearch.Add("02");

// same as your code

var result = datas.Where(i => dataSearch.Contains(i[0])).ToList();

答案 1 :(得分:-1)

如果List<List<string>>中的三个项目具有紧密绑定的关系,最好为此创建一个类,然后列出这些对象。

Class StationaryItem
         {
           int ItemCode;
           String ItemName;
           float Price;

         public StationaryItem(int Code, string ItemName,float Price)
            {
              this.ItemCode = Code;
              this.ItemName = ItemName;
              this.Price = Price;
            }
         }

public static void Main ()
      {
         List<StationaryItem> ItemList = new List<StationaryItems>
         ItemList.Add( new StationaryItem(01,"Pen",20));
         ItemList.Add( new StationaryItem(02,"Pencil",5));

         //After you make a class like this you can use Linq to manuplate easily
      }