'How to retrieve firstordefault from a ToList in linq
I have the following table in sql

I am trying to select all records with a status of onboard, but however you can see thatfor user '43d658bc-15a7-4056-809a-5c0aad6a1d86' i have two onboard entries. How do i select the firstordefault entry if the user has more than one record?
so my expected outcome should be

this is what i have that gets all the records
public async Task<List<Model>> HandleAsync(Query query)
{
return (await _repository.GetProjectedListAsync(q=> q.Where(x => x.Status== "Onboard").Select( Project.Log_Model))).ToList();
}
internal static partial class Project
{
public static readonly Expression<Func<Log,Model>> Log_Model =
x => x == null ? null : new Model
{
Id = x.Id,
UserId = x.UserId,
Status = x.Status,
created=x.Created,
DepartmentId=x.DepartmentId
};
}
i tried the following
var test = (await _repository.GetProjectedListAsync(q=> q.Where(x => x.Status== "Onboard").Select( Project.Log_Model))).ToList();
var t= test.FirstOrDefault();
return t;
but i get an error "can not implicitly convert type model to system.collections.generic.list"
Solution 1:[1]
The following code example demonstrates how to use FirstOrDefault() by passing in a predicate. In the second call to the method, there is no element in the array that satisfies the condition. You can filter out an entry you are looking for directly in the FirstOrDefault().
If you don't want to have duplicates, you could also use Distinct.
string[] names = { "Hartono, Tommy", "Adams, Terry",
"Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
string firstLongName = names.FirstOrDefault(name => name.Length > 20);
Console.WriteLine("The first long name is '{0}'.", firstLongName);
string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30);
Console.WriteLine(
"There is {0} name longer than 30 characters.",
string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a");
/*
This code produces the following output:
The first long name is 'Andersen, Henriette Thaulow'.
There is not a name longer than 30 characters.
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Flimtix |
