Reputation: 4297
ID Value
20 200
20 300
10 100
10 050
I need to get the Biggest ID which has the biggest value, and then store target ID and its value. In above example the output should be (ID=20,Value=300). I know I can use Max but it seems I can not use && to check two value.
Upvotes: 0
Views: 48
Reputation: 1225
Depending on collection type you use and the size of the collection it might be better to use approach like this:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var fooList = new List<Foo>
{
new Foo { Id = 20, Value = 200 },
new Foo { Id = 20, Value = 300 },
new Foo { Id = 10, Value = 100 },
new Foo { Id = 10, Value = 050 }
};
var maxId = fooList.Max(f => f.Id);
var maxValue = fooList.Where(f => f.Id == maxId).Max(f => f.Value);
Console.WriteLine("Max Id = {0}", maxId);
Console.WriteLine("Max value = {0}", maxValue);
}
public class Foo
{
public int Id { get; set; }
public int Value { get; set; }
}
}
But @2kay s method would work just fine for demonstration purposes on any collection of decent size.
Upvotes: 1
Reputation: 9214
Seems like you need to use OrderBy
:
var biggestByIdAndValue = values.OrderByDescending(x => x.Id)
.ThenByDescending(x => x.Value)
.FirstOrDefault();
Upvotes: 1