[英]Question about length of an object in LINQ
我有一個清單。 我想打印最長的地址。
偽碼
foreach (var i in listAddr)
{
// access listAddr.Address.Length
// print longest address
// print shortest address
}
非常粗略,沒有foreach:
var sortedAddr = listAddr.OrderBy(x => x.Address.Length);
var longestAddr = sortedAddr.Last();
var shortedAddr = sortedAddr.First();
正如喬恩所說,這具有O(n log n)的復雜性。 但是,如果您沒有極端的性能需求,那可能是合理的。
編輯:
如果您有很多相同長度的地址,則可以執行以下操作:
var sortedGroups = listAddr.GroupBy(x => x.Address.Length).OrderBy(x => x.Key);
var longestAddresses = sortedGroups.Last();
var shortestAddresses = sortedGroups.First();
// just print iterating over longestAddresses and shortestAddresses ...
聽起來您想要MaxBy
和MinBy
功能,例如
var maxEntry = listAddr.MaxBy(entry => entry.Address.Length);
Console.WriteLine(maxEntry.Address);
var minEntry = listAddr.MinBy(entry => entry.Address.Length);
Console.WriteLine(minEntry.Address);
不幸的是,在普通的LINQ to Objects中沒有這樣的東西,但是我們在MoreLINQ中有一個實現,我相信Reactive Extensions在System.Interactive中也有一個實現。
顯然,您可以按地址大小遞減的順序進行排序,然后得出第一個結果...將是O(n log n)而不是O(n)復雜度...在大多數情況下可能很好。 雖然這對我來說很不雅:)
來自MaxBy的MoreLINQ實現的MaxBy
(不帶注釋:)
public static TSource MaxBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> selector)
{
return source.MaxBy(selector, Comparer<TKey>.Default);
}
public static TSource MaxBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
source.ThrowIfNull("source");
selector.ThrowIfNull("selector");
comparer.ThrowIfNull("comparer");
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource max = sourceIterator.Current;
TKey maxKey = selector(max);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, maxKey) > 0)
{
max = candidate;
maxKey = candidateProjected;
}
}
return max;
}
}
}
這應該工作list.Max(x => x.Address)
和list.Min(x => x.Address)
例如,如果您有這樣的列表
List<int> myList = new List<int>();
您可以使用myList.Max()和myList.Min()來獲取最大值和最小值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.