Reputation: 303
I have a class as shown below, in that class there is one to one mapping between Amount array, and date's array indexes, so there length will always be same.
I have to get the maximum amount from Amount[] where Date1 > DateTime.Today & DateTime.Today < Date2 < @OneParameterDate.
How can this be done using linq?
public class TestClass
{
public string ID { get; set; }
public decimal[] Amount { get; set; }
public DateTime[] Date1 { get; set; }
public DateTime[] Date2 { get; set; }
public DateTime[] Date3 { get; set; }
public string Name { get; set; }
}
Upvotes: 0
Views: 60
Reputation: 43876
Charles Mager's comment points in the correct direction. But if you're not willing to change your code in that way, this should give you the result you want:
decimal maxAmount = Enumerable.Range(0, Amount.Length)
.Where(i => Date1[i] > DateTime.Today &&
Date2[i] > DateTime.Today &&
Date2[i] < OneParameterDate)
.Max(i => Amount[i]);
Enumerable.Range
iterates through the array indices, Where
filters for those indices where your condition (as I understood it from your question) is met.
From these filtered indices, Max
selects the maximum amount value.
Upvotes: 2
Reputation: 37299
If you can, a better representation will be to have a class like this:
public class ClassA
{
public decimal Amount { get; set; }
public DateTime Date1 { get; set; }
public DateTime Date2 { get; set; }
public DateTime Date3 { get; set; }
}
And then you have a IEnumerable<ClassA>
in your TestClass
. Now You can do linq queries on it.
records.Where(record.Date1 < DateTime.Today &&
DateTime.Today < record.Date2 &&
record.Date2 < @SomeParameter)
.Max(record.Amount);
Upvotes: 2