You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LINQ查询中从多对象列表提取属性到UserModel?

How to Populate UserModel.Names with First Language Name and Top 2 Skill Names Using LINQ

Got it, let's work through this LINQ problem together. You need to combine the first language name (if the user has any languages) and up to two skill names (if the user has skills) into the Names list of your UserModel. Here's a clean way to implement this:

List<UserModel> models = context.Users.Select(x => new UserModel 
{ 
    Id = x.Id, 
    Names = Enumerable.Empty<string>()
        // Add first language name (if exists)
        .Concat(x.Languages?.Take(1).Select(lang => lang.Name) ?? Enumerable.Empty<string>())
        // Add top 2 skill names (if exist)
        .Concat(x.Skills?.Take(2).Select(skill => skill.Name) ?? Enumerable.Empty<string>())
        .ToList()
}).ToList();

Let's break down what each part does:

  • Handling the first language: x.Languages?.Take(1).Select(lang => lang.Name) grabs the first language's name only if the Languages list isn't null. The null-conditional operator (?.) prevents null reference errors, and ?? Enumerable.Empty<string>() ensures we don't add anything if Languages is null or empty.
  • Handling top 2 skills: x.Skills?.Take(2).Select(skill => skill.Name) works the same way, but takes up to two skill names instead of one.
  • Combining everything: We start with an empty sequence (Enumerable.Empty<string>()), use Concat() to append the language name (if present) followed by the skill names, then convert the combined sequence to a List<string> with ToList().

Alternative (slightly more explicit) version:

If you prefer initializing a new list first instead of using Enumerable.Empty<string>(), this works too:

Names = new List<string>()
    .Concat(x.Languages?.Take(1).Select(lang => lang.Name) ?? Enumerable.Empty<string>())
    .Concat(x.Skills?.Take(2).Select(skill => skill.Name) ?? Enumerable.Empty<string>())
    .ToList()

Either way, this will correctly populate Names with the required values—no extra null checks needed, and it handles empty lists gracefully.

内容的提问来源于stack exchange,提问作者Miguel Moura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:34