生成给定字符串的列表子列表

时间:2022-07-17 19:03:57

I am very new to LINQ and am wondering if there is a way to extract a sublist from a list of strings given that the string values are provided beforehand.

我是LINQ的新手,我想知道是否有办法从字符串列表中提取子列表,因为事先提供了字符串值。

For example, if I have:

例如,如果我有:

var movies = new List<Movie>
{
    new Movie { Name = "Noah" },
    new Movie { Name = "Terminator" },
    new Movie { Name = "Troy" },
    new Movie { Name = "Gladiator" },
};

I would like to use LINQ to create a sublist if I provide the Name strings "Noah" and "Troy".

如果我提供Name字符串“Noah”和“Troy”,我想使用LINQ创建子列表。

I have tried googling and results point me to SelectMany and GroupBy but all of the examples involve lists that contains primitive values, not primitives values contained in objects.

我已经尝试了谷歌搜索,结果将我指向SelectMany和GroupBy,但所有示例都涉及包含原始值的列表,而不是包含在对象中的原始值。

3 个解决方案

#1


Using Linq lambda it would be:

使用Linq lambda它将是:

var result = movies.where(x => x.Name == "Troy" || x.Name == "Noah");

This would return a IEnumerable<Movie> containing the ones searched for using Where.

这将返回包含使用Where搜索的IEnumerable

#2


Is this what you are looking for?

这是你想要的?

var sublistItems = new List<string>() {"Noah", "Troy"} ;
var subList = movies.where(m=> sublistItems.Contains(m.Name));

#3


var newlist = from m in movies
              where (m.Name == "Troy" || m.Name == "Noah")
              select m;

#1


Using Linq lambda it would be:

使用Linq lambda它将是:

var result = movies.where(x => x.Name == "Troy" || x.Name == "Noah");

This would return a IEnumerable<Movie> containing the ones searched for using Where.

这将返回包含使用Where搜索的IEnumerable

#2


Is this what you are looking for?

这是你想要的?

var sublistItems = new List<string>() {"Noah", "Troy"} ;
var subList = movies.where(m=> sublistItems.Contains(m.Name));

#3


var newlist = from m in movies
              where (m.Name == "Troy" || m.Name == "Noah")
              select m;