LCJ
LCJ

Reputation: 22652

Specify condition with FirstOrDefault (in Method Chaining Approach)

I have following code for selecting latest Preference object’s CreatedDate. It uses FirstOrDefault to select one Preference object from preferences collection.

DateTime? latestPreferenceDate = preferences.FirstOrDefault() == null ? null : (preferences.FirstOrDefault()).CreatedDate;

How can we specify that the selected object should be the one with the latest Created Date? Also, I need to select the object corresponding to latest date for selecting other properties of this object.

Note: I am looking for a method chaining approach

CODE

class Program
{
    static void Main()
    {
        Int16? test = null;
        string val = Convert.ToString(test);

        Collection<Preference> preferences = new Collection<Preference>();

        Preference pref1 = new Preference();
        pref1.CreatedDate = new DateTime(2011, 11, 11);
        pref1.PreferenceCode = 1;

        Preference pref2 = new Preference();
        pref2.CreatedDate = new DateTime(2012, 12, 12);
        pref2.PreferenceCode = 2;

        preferences.Add(pref1);
        preferences.Add(pref2);


        DateTime? latestPreferenceDate = preferences.FirstOrDefault() == null ? null : (preferences.FirstOrDefault()).CreatedDate;


    }



}

public class Preference
{
    public DateTime? CreatedDate { get; set; }
    public int PreferenceCode { get; set; }
}

REFERENCES:

  1. Using "where": Cannot convert lambda expression to type 'bool'
  2. .NET LINQ query syntax vs method chain

Upvotes: 1

Views: 2887

Answers (5)

Habib
Habib

Reputation: 223237

You may get the LatestDate from the table and then use that in your condition.

if(preferences != null)
{
 if(preferences.Count != 0)
 {
    var LatestDate = preferences.Max(r=> r.CreatedDate);
    var item = preferences.FirstOrDefault(r=> r.CreatedDate == LatestDate);
 }
}

Or in one line you can do:

if(preferences != null)
{
 if(preferences.Count != 0)
 {

    var item = preferences.FirstOrDefault(r=> r.CreatedDate == 
                                          preferences.Max(t=> t.CreatedDate));
}
}

Upvotes: 2

Jignesh Thakker
Jignesh Thakker

Reputation: 3698

Try like below,

Use MAX to find maxt CreatedDate.

DateTime? latestPreferenceDate = null;
var LatestDate = preferences.Max(r=> r.CreatedDate);

Now Find all Records which have CreatedDate = LatestDate.

var items = preferences.Where(r=> r.CreatedDate !=null && r.CreatedDate == LatestDate);

If there are many records with LatestDate (you will get multiple items with LatestDate) then you can use FirstOrDefault to get first occurrence and LastorDefault for Last occurrence.

   if (items != null && items.Count > 0)
   {
      var first = items.FirstOrDefault();
      if (first != null)
      {
         latestPreferenceDate = first.CreateDate();
      }
      //For Last
      var last = items.FirstOrDefault();
      if (last != null)
      {
            latestPreferenceDate = last.CreatedDate();
      }

    }

If you want only last item which has LatestDate then try with below code:

var item= preferences.Where(x=>x.CreatedDate !=null).
                  OrderbyDescending(x=>x.CreatedDate).
                  FirstOrDefault();

if (item != null)
{
   latestPreferenceDate  = item.CreatedDate;
}

Upvotes: 0

Steve
Steve

Reputation: 20469

var c = preferences.OrderBy(x => x.CreatedDate).Reverse().FirstOrDefault();

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

DateTime? latestPreferenceDate = preferences.Max(p => p.CreatedDate)

Also if you want to get preference with latest date you can use MoreLINQ (available from NuGet) extension MaxBy:

var item = preferences.MaxBy(p => p.CreatedDate)

It is implemented this way (avoids enumerating sequence twice):

public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source,
    Func<TSource, TKey> selector)
{
    IComparer<TKey> comparer = Comparer<TKey>.Default;
    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;
    }
}

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

try like this

   var data= preferences.Where(x=>x.CreatedDate !=null).
                  Orderby(x=>x.CreatedDate).
                  FirstOrDefault() ;
    if(data!=null)
      var date = data.CreatedDate;

Upvotes: 1

Related Questions