How to take more than one qualifying record
var sortedAddr = listAddr.OrderBy(x => x.Address.Length);
var longestAddr = sortedAddr.Last();
var shorte开发者_运维知识库dAddr = sortedAddr.First();
Now if the longestaddr
contains more than one records with the same length, the above piece of code prints only one. However how to print multiple longest address?
You can get the length of the longest address and use TakeWhile
var sortedDesc = listAddr.OrderByDescending(x => x.Address.Length);
int longestAddress = sortedDesc.First().Address.Length;
var longest = sortedDesc.TakeWhile(x => x.Address.Length == longestAddress);
Alternatively you could group by address length and then get the 'largest' group:
var longest = listAddr.GroupBy(x => x.Address.Length)
.Max(grp => grp.Key);
EDIT: To print them out you can just loop through the collection of largest addresses:
foreach(var address in longest.Select(x => x.Address))
{
System.Console.WriteLine("Address: {0}, length: {1}", address, address.Length);
}
I would probably start with the following code.
var minLength = listAddr.Min(y => y.Address.Length);
var maxLength = listAddr.Max(y => y.Address.Length);
var shortestAddr = listAddr.Where(x => x.Address.Length == minLength);
var longestAddr = listAddr.Where(x => x.Address.Length == maxLength);
It contains only a single optimization - pre-calculating the minimum and maximum length keeping the runtime linear instead of becoming quadratic.
Pre-sorting the list takes at least O(n log(n))
and you only access it a few times after this expensive operation. You can of course do it and use Where()
or TakeWhile()
to get the desired addresses but this will make the code harder to read and probably even slower.
精彩评论