【问题标题】:Extracting only one property in List<Object> to List<String>仅将 List<Object> 中的一个属性提取到 List<String>
【发布时间】:2023-01-05 17:31:06
【问题描述】:

 public async Task<IEnumerable<String>> GetUsersAsStringBysearch(string userSearch)
        {
           //This returns List<UserTable>
            var item = await riskDBContext.UserTables.Where(e => e.Email.Contains(userSearch)).ToListAsync(); ;
            List<string> m_oEnum = new List<string>();
            foreach (var user in item)
            {
                m_oEnum.Add(user.Email);
            }
            //this is when we fullyindex the table
            //var item = await riskDBContext.UserTables.Where(x => EF.Functions.FreeText(x.Email,userSearch)).ToListAsync();

            return m_oEnum;
        }

var item = await riskDBContext.UserTables.Where(e => e.Email.Contains(userSearch)).ToListAsync(); ;

返回List&lt;UserTable&gt;,我只想要电子邮件 ID 作为List&lt;string&gt;

有没有一行语句可以实现,而不是循环列表并将其添加到 List&lt;String&gt;

【问题讨论】:

  • 您可以将其写为return item.Select(user =&gt; user.Email),但请注意,它在内部与您的代码一样工作。所以这只是句法上的一行。

标签: c#


【解决方案1】:

使用.Select(e =&gt; e.Email)创建投影

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多