我有个问题。我有一个类的Cars,我需要显示在一个简单的字符串,如果他们将出售或不基于他们的号码。
就像这样:
Public Class Car
Property Index As Integer
Property Sell As Boolean
End Class
Public Class Cars
Property Vehicles As New List(Of Car) From {
{New Car With {.Index = 1, .Sell = True}},
{New Car With {.Index = 2, .Sell = False}},
{New Car With {.Index = 3, .Sell = True}},
{New Car With {.Index = 4, .Sell = True}},
{New Car With {.Index = 5, .Sell = True}},
{New Car With {.Index = 6, .Sell = False}},
{New Car With {.Index = 7, .Sell = True}},
{New Car With {.Index = 8, .Sell = True}},
{New Car With {.Index = 9, .Sell = False}},
{New Car With {.Index = 10, .Sell = False}},
{New Car With {.Index = 11, .Sell = True}}}
End Class我想显示这样一个简单的字符串:汽车待售: 1,3-5,7-8,11,这是基于.Sell的值。
在.NET中是否有某种启发式方法来创建这种字符串,还是仅仅是一堆for/each和if/然后,以及数组的重调?
发布于 2010-10-04 01:48:38
LINQ肯定会简化解决方案。没有LINQ,您可以使用StringBuilder并在列表上进行迭代,同时比较相邻项并构建字符串。这将是更理想的,而不是重新调光数组等。
以下是LINQ解决方案:
Dim query = vehicles.Where(Function(c) c.Sell) _
.OrderBy(Function(c) c.Index) _
.Select(Function(c, i) New With { .Car = c, .Diff = c.Index - vehicles(i).Index }) _
.GroupBy(Function(item) item.Diff) _
.Select(Function(item) item.First().Car.Index.ToString() &
If(item.Count() > 1, "-" & item.Last().Car.Index.ToString(), ""))
Console.WriteLine("Cars to be sold: " & String.Join(", ", query.ToArray()))使用.NET 4,您可以删除ToArray()调用,因为String.Join具有接受IEnumerable<T>的重载。
代码过滤掉Sell值为True的汽车。为了使列表正常工作,列表必须按照Car.Index的顺序排列,因此OrderBy是重要的。确定连续项的逻辑是比较相邻项并根据它们的索引差异对它们进行分组。如果有1的差别,那么他们就是邻居。因此,第二个Select项目为匿名类型,根据当前索引存储Car和Diff,减去前一个car的索引。GroupBy将所有差异组合在一起。最后一个Select构建范围。如果Count大于1,则在第一个组项和最后一个组项之间放置一个破折号。否则,一个项目存在,我们选择它的原样。最后,我们使用String.Join返回以逗号分隔的值列表。
发布于 2010-10-04 01:24:28
我会这么做:
Dim list_sold = Vehicles.Where(Function(x As Car) x.Sell = True)
Dim list_index = list_sold.Select(Function(x As Car) x.Index.ToString())
Console.WriteLine("Cars to be sold: {0}", String.Join(", ", list_index))https://stackoverflow.com/questions/3852114
复制相似问题