Reputation:
I have a routine where I am accessing a table in the database and creating a model from the data.
Database Table TblUNote
ID Quarter Year SubID Data
1 1 2007 245 DataPoint1
2 1 2007 245 Datapoint2
3 1 2007 245 Datapoint3
4 1 2007 247 DataPoint1
5 1 2007 247 Datapoint2
6 1 2007 247 Datapoint3
7 1 2007 249 DataPoint1
8 1 2007 249 Datapoint2
The routine is
public RData[] GetData(int Q, int Y)
{
using (Entities be = new Entities())
{
List<RData> nlist = new List<RData>();
List<TblUNote> info = be.TblUNotes.Where(a => a.Quarter == Q && a.Year == Y).ToList();
foreach (var item in info)
{
Rdata newmodel = new RData()
{
//create model
};
}
nlist.Add(newmodel);
}
return(nlist).ToArray();
}
This works, but now I need to modify it so that only one model entry is created for each SubID. I have tried using .Distinct() but I just get the same data. I tried to use .First() but I keep getting an error no matter where I put it in the database call. I need the model list to have
RData Model
Item1 Quarter = 1, Year = 2007, SubID = 245, Data = DataPoint1
Item2 Quarter = 1, Year = 2007, SubID = 247, Data = DataPoint1
Item3 Quarter = 1, Year = 2007, SubID = 249, Data = DataPoint1
The problem is I have nothing to compare SubID to. I thought .Distinct() would have given me a way to do this. I am sure that .First should but how do I integrate it into the database call.
Upvotes: 0
Views: 75
Reputation: 60503
You can use a GroupBy, and take first item of each group :
be.TblUNotes
.Where(a => a.Quarter == Q && a.Year == Y)
.GroupBy(m => m.SubId)
.Select(g => g.FirstOrDefault())//or g.OrderBy(m => m.Data).FirstOrDefault(), for example, I don't know which item you wanna take
.ToList();
Upvotes: 1