首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >针对给定场景使用Linq

针对给定场景使用Linq
EN

Stack Overflow用户
提问于 2014-02-14 13:40:48
回答 2查看 33关注 0票数 0

我是LINQ的新手,我的TL给了我一个要求,我可以在几秒钟内完成,因为它是一个基本的,我想要的代码转换成LINQ,请帮助我。

代码语言:javascript
复制
foreach (var item in query)
            {
                profileSearchResultEntity = new ProfileSearchResultEntity();
                profileSearchResultEntity.Id = item.ProfileId;

                if (String.IsNullOrEmpty(item.DisplayName))
                {
                    profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName;
                }
                else
                {
                    profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName +" "+"-"+" "+ item.DisplayName;
                }     


                lstProfileSearchResultEntity.Add(profileSearchResultEntity);
            }
            return lstProfileSearchResultEntity;

如何使用LINQ或Lambda满足此条件?

EN

回答 2

Stack Overflow用户

发布于 2014-02-14 13:52:21

代码语言:javascript
复制
var lstProfileSearchResultEntity = 
    query.Select(i => new ProfileSearchResultEntity 
        {
            Id = i.Id,
            Name = i.LastName + "," + " " + i.FirstName + 
                       (string.IsNullOrEmpty(i.DisplayName) ? "" : " - " + i.DisplayName)
        }).ToList();
票数 1
EN

Stack Overflow用户

发布于 2014-02-14 13:52:16

这就是它:

代码语言:javascript
复制
   return query.Select(item =>
                     {

                         var profileSearchResultEntity = new ProfileSearchResultEntity{Id = item.ProfileId};
                         if (String.IsNullOrEmpty(item.DisplayName))
                         {
                             profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName;
                         }
                         else
                         {
                             profileSearchResultEntity.Name = item.LastName + "," + " " + item.FirstName + " " +
                                                              "-" + " " + item.DisplayName;
                         }
                         return profileSearchResultEntity;
                     });

我要展示的是,您可以编写一个函数来初始化新选择的对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21771653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档