【问题标题】:Linq subquery with in a query在查询中使用 Linq 子查询
【发布时间】:2012-01-19 12:50:03
【问题描述】:

我有两个列表,我必须从中获取两个值(MyCaption 和 MyValue)。

List<UserInfoModel> userInfo = new List<UserInfoModel>();

List<myuser_field> myUserFields = GetMyUserFields();
var otherUserFields = otherUserService.GetOtherUserFields();

userInfo = (from otherUserField in otherUserFields
               where otherUserField.Chosen == true 
                    select new UserInfoModel {
                        MyCaption = otherUserField.FieldAlias,
                        MyValue =
                    }).ToList();

MyCaption 我直接从列表之一中获取。现在要获取 MyValue,我需要根据 otherUserField.FieldName 查找。 即我必须找到等于 otherUserField.FieldName 的 myUserFields.FieldName 并将其分配给 MyValue。

可以在上面的单个查询中完成吗?请推荐

【问题讨论】:

标签: asp.net linq c#-4.0


【解决方案1】:
userInfo = (from myUserField in myUserFields
            join otherUserField in otherUserFields
            on myUserField.FieldName == otherUserField.FieldName
            where otherUserField.Chosen == true 
            select new UserInfoModel {
                MyCaption = otherUserField.FieldAlias,
                MyValue = myUserField.FieldName
            }).ToList();

【讨论】:

    【解决方案2】:

    从您的问题来看,您要分配给 MyValue 的内容不是很清楚。

    以下将分配具有与当前枚举的 myuser_object (otherUserField.FieldName) 的 FieldName 匹配的 FieldName 的 myuser_field 对象:

    List<UserInfoModel> userInfo = new List<UserInfoModel>(); 
    
    List<myuser_field> myUserFields = GetMyUserFields(); 
    var otherUserFields = otherUserService.GetOtherUserFields(); 
    
    userInfo = (from otherUserField in otherUserFields 
                   where otherUserField.Chosen == true  
                        select new UserInfoModel { 
                            MyCaption = otherUserField.FieldAlias,
                            MyValue = myUserFields.Single(uf => uf.FieldName == otherUserField.FieldName)
                        }).ToList(); 
    

    【讨论】:

    • 请注意,如果 myUserFields 中没有或多个对应的对象,您将收到异常。使用 SingleOrDefault 代替 Single,在这种情况下将 null 分配给 MyValue。
    猜你喜欢
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多