C# 在列表中使用 Linq 选择列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14663971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:38:17  来源:igfitidea点击:

Using Linq select list inside list

c#.netlinq

提问by Reno

Using LINQ how to select from a List within a List

使用 LINQ 如何从列表中的列表中进行选择

public class Model
{
    public string application { get; set; }

    public List<Users> users { get; set; }
}

public class Users
{
    public string name { get; set; }

    public string surname { get; set; }
}

List<Model> list = new List<Model>();

I need to select list where application = "applicationame" and users where surname = "surname" into one list.

我需要选择列表 where application = "applicationame" 和 users where surname = "surname" 到一个列表中。

采纳答案by Tim Schmelter

If you want to filter the models by applicationnameand the remaining models by surname:

如果您想通过以下方式过滤模型applicationname和其余模型surname

List<Model> newList = list.Where(m => m.application == "applicationname")
    .Select(m => new Model { 
        application = m.application, 
        users = m.users.Where(u => u.surname == "surname").ToList() 
    }).ToList();

As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.

如您所见,它需要创建新模型和用户列表,因此这不是最有效的方法。

If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any:

如果您不想过滤用户列表,而是按至少有一个用户并具有给定用户名的用户过滤模型,请使用Any

List<Model> newList = list
    .Where(m => m.application == "applicationname"
            &&  m.users.Any(u => u.surname == "surname"))
    .ToList();

回答by Cédric Bignon

You have to use the SelectManyextension method or its equivalent syntax in pure LINQ.

您必须SelectMany在纯 LINQ 中使用扩展方法或其等效语法。

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

回答by I4V

list.Where(m => m.application == "applicationName" && 
           m.users.Any(u => u.surname=="surname"));

if you want to filterusers as TimSchmelter commented, you can use

如果您想按照 TimSchmelter 的评论过滤用户,您可以使用

list.Where(m => m.application == "applicationName")
    .Select(m => new Model
    {
        application = m.application,
        users = m.users.Where(u => u.surname=="surname").ToList()
    });

回答by It'sNotALie.

After my previous answer disaster, I'm going to try something else.

在我之前的答案灾难之后,我将尝试其他方法。

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));