我有一个清单。我想打印最长的地址。
伪代码
foreach (var i in listAddr)
{
// access listAddr.Address.Length
// print longest address
// print shortest address
}
答案 0 :(得分:4)
非常粗略,没有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 ...
答案 1 :(得分:2)
听起来您需要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
的{{3}}的代码(没有评论:)
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;
}
}
}
答案 2 :(得分:0)
这应该有效list.Max(x => x.Address)
和list.Min(x => x.Address)
答案 3 :(得分:0)
例如,如果您有一个类似的列表
List<int> myList = new List<int>();
您可以使用myList.Max()和myList.Min()来获取最大值和最小值