如何在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 theLanguageslist isn't null. The null-conditional operator (?.) prevents null reference errors, and?? Enumerable.Empty<string>()ensures we don't add anything ifLanguagesis 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>()), useConcat()to append the language name (if present) followed by the skill names, then convert the combined sequence to aList<string>withToList().
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
相关产品推荐
相关产品推荐

