C
C#6mo ago
UntoldTitan

✅ Combining a List inside of a Select

I have an object:
public class BackendSuccess
{
[Key]
public int id { get; set; }
public DateTime creationDate { get; set; }
public ICollection<Label> labels { get; set; } = new List<Label>(); // BEEEEG list of base64 encoded labels
}
public class BackendSuccess
{
[Key]
public int id { get; set; }
public DateTime creationDate { get; set; }
public ICollection<Label> labels { get; set; } = new List<Label>(); // BEEEEG list of base64 encoded labels
}
And when i want to grab them all from the database, I want them combined by creationDate using LINQ. For example: creationDate:2023-12-15, labels:[{1},{2}] and creationDate:2023-12-15, labels:[{3},{4}] would combine to create creationDate:2023-12-15, labels:[{1},{2},{3},{4}] The order of the elements in labels doesn't matter, I just want them combined.
4 Replies
Angius
Angius6mo ago
var stuff = await _context.Labels
.GroupBy(l => l.BackendSuccess.CreationDate)
.Select(g => new ThingDto {
CreationDate = g.Key,
Labels = g.Select(l => l.Id)
})
.ToListasync();
var stuff = await _context.Labels
.GroupBy(l => l.BackendSuccess.CreationDate)
.Select(g => new ThingDto {
CreationDate = g.Key,
Labels = g.Select(l => l.Id)
})
.ToListasync();
Something like that?
UntoldTitan
UntoldTitan6mo ago
Lemme try that I put that in, im just converting the DateTime to a DateOnly so that they'll actually match lol made some changes, this is what I have now @ZZZZZZZZZZZZZZZZZZZZZZZZZ,
return await _context.Successes
.GroupBy(l => l.creationDate)
.Select(p => new BackendSuccess { creationDate = p.Key, labels = (ICollection<Label>)p.Select(l => l.labels) })
.ToListAsync();
return await _context.Successes
.GroupBy(l => l.creationDate)
.Select(p => new BackendSuccess { creationDate = p.Key, labels = (ICollection<Label>)p.Select(l => l.labels) })
.ToListAsync();
(ICollection<Label>)p.Select(l => l.labels) seems to be an ICollection<ICollection<>> tho, why would that be?
Angius
Angius6mo ago
Because each success has a collection of labels, and each group will be a collection of those collections That's why I went through label and not success You can use .SelectMany() instead of .Select() there That'll flatten it
UntoldTitan
UntoldTitan6mo ago
ohhh, i didnt notice that XD ok, ty it works!! thank you so much!