I am having a bear of a time getting this to work. I have a List(Of MyItem)
called Items
that have a OrderId
property on them. From those items, I want to create a list开发者_StackOverflow of Order
s. Some items will have the same OrderId
so I want to try to group by OrderId
. I then want to sort by date. Here's what I have so far:
Public ReadOnly Property AllOrders() As List(Of Order)
Get
Return Items.Select(Function(i As MyItem) New Order(i.OrderID)) _
.GroupBy(Function(o As Order) New Order(o.OrderID)) _
.OrderBy(Function(o As Order) o.DateOrdered).ToList
End Get
End Property
This, of course, doesn't compile, and I get the error:
Value of type 'System.Collections.Generic.List(Of System.Linq.IGrouping(Of Order, Order))' cannot be converted to 'System.Collections.Generic.List(Of Order))'
I've bolded the part where I think the problem is, but I have no idea how to fix it. Also, it used to work fine (except there were duplicate values) before I added the .GroupBy
statement. Anyone have any ideas?
Thanks
EDIT
Basically, I want this:
List of Existing Items Take List and Turn it into List(Of MyItem): List(Of Order): ItemId OrderId OrderID 1 100 100 2 102 102 3 100
You don't need to use group by for this.
Public ReadOnly Property AllOrders() As List(Of Order)
Get
Return Items.Select(Function(i) i.OrderID).Distinct.Select(Function(p) New Order(p)).ToList()
End Get
End Property
If you want to order it by the OrderedDate on the order, just add an orderby clause before the ToList
Public ReadOnly Property AllOrders() As List(Of Order)
Get
Return Items.Select(Function(i) i.OrderID).Distinct _
.Select(Function(p) New Order(p)) _
.OrderBy(Function(s) s.DateOrdered).ToList()
End Get
End Property
By putting the OrderBy after the GroupBy, you are instructing it to sort the groups. A group of Orders doesn't have a single date. I'm thinking what you probably want to do is switch the OrderBy and GroupBy around; unless GroupBy loses any prior sort order, in which case you'll have to sort each Group.
This also looks wrong to me
.GroupBy(Function(o As Order) New Order(o.OrderID))
Should it not be
.GroupBy(Function(o As Order) o.OrderID)
I said F it and used some less pretty code:
Public ReadOnly Property AllOrders() As List(Of Order) Get Dim ids = Items.Select(Function(i As OrderItem) i.OrderID).Distinct() Dim orders As New List(Of Order) For Each i As Integer In ids orders.Add(New Order(i)) Next Return orders.OrderBy(Function(o As Order) o.DateOrdered).ToList End Get End Property
If anyone has a LINQier way of doing it, I would prefer to do it that way. Otherwise, I guess this piece of kludge will have to do.
精彩评论