Reputation: 133
I know this question has been asked many times and I know that the Distinct call destroys the previous order so I must use the OrderBy afterwards, but in this case I must be doing something else wrong.
int[] resources = (from a in context.Beamline_Requests
join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID
where b.Beamtime_Request_ID == id
select a.Beamline_ID).Distinct().OrderBy(a => a.ID).ToArray();
I receive the:
Cannot convert lambda expression to type 'System.Linq.Expressions.LambdaExpression' because it is not a delegate type
error message on the OrderBy
. It also says:
'int' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
So apparently the 'a' is no longer part of the context.
I have done similar things successfully but in those cases I am projecting the Linq into a ViewModel so in this case it must have something to do with attempting to just make it an array.
Upvotes: 1
Views: 162
Reputation: 223207
You are only selecting field Beamline_ID
and later you are trying to OrderBy ID
, Your intermediate result from select doesn't have field ID
it is just a projection of int
numbers. As @GrantWinney suggested you can do OrderBy(a=> a)
like:
int[] resources = (from a in context.Beamline_Requests
join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID
where b.Beamtime_Request_ID == id
select a.Beamline_ID).Distinct().OrderBy(a => a).ToArray();
For the comment:
My issue though is that I actually do need to order by the ID, not the Beamline_ID even though I only need the Beamline_ID in the array.
int[] resources = (from a in context.Beamline_Requests
join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID
where b.Beamtime_Request_ID == id
select new
{
Beamline_ID = a.Beamline_ID,
ID = b.ID
})
.OrderBy(a => a.ID)
.Select(r=> r.Beamline_ID)
.Distinct()
.ToArray();
Or in a simpler version you can achieve:
int[] resources = (from a in context.Beamline_Requests
join b in context.Technique_Requests on a.Technique_Request_ID equals b.ID
where b.Beamtime_Request_ID == id
orderby b.ID
select a.Beamline_ID)
.Distinct()
.ToArray();
Upvotes: 4