使用LINQ里面选择列表列表 [英] Using Linq select list inside list

查看:66
本文介绍了使用LINQ里面选择列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ如何从一个List一个List

Using LINQ how to select from a List within a List

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>();



我需要选择列表,应用程序=applicationame和使用者,其中姓=姓成一个名单。

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

推荐答案

如果您想通过的applicationName 来筛选模型和通过其余型号:

If you want to filter the models by applicationname and the remaining models by 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:

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

这篇关于使用LINQ里面选择列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆