LINQ "MaxOrDefault"?

I'm new to LINQ. I need to compute new_id as follows:

public class C_Movement
{
  public int id=-1;
  public static ObservableCollection<C_Movement> list=new ObservableCollection<C_Movement>();
  // ...
}

int new_id = (C_Movement.list.Count==0) ? 0 : C_Movement.list.Max(x => x.id)+1;

Is there a LINQ way to compact that expression, so that I don't have to use the ? : structure? The problem is that, when C_Movement.list contains no elements, C_Movement.list.Max(x => x.id) returns null (and I would like it to return -1, instead).

Thank you.

DefaultIfEmpty method should help:

int new_id = C_Movement.list.Select(x => x.id).DefaultIfEmpty(-1).Max()+1;

Language-Integrated Query (LINQ) (C#), Education Software Built for Everyone in Your District. Whether you are a Superintendent, Nutrition Director, IT Manager or Financial Officer, LINQ has a solution� Lowest Rates. Biggest Selection. Easiest Booking. Save Up To 60% w/ Hotwire®.

int new_id = C_Movement.list.Max(x => (int?)x.id).GetValueOrDefault(-1) + 1;

where GetValueOrDefault is a method of Nullable<T>.

The LINQ Las Vegas Strip Hotel + Experience, Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ ( Language Integrated Query) allows writing queries even without the knowledge of� Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

How about:

int new_id = 0;

if (C_Movement.list.Any())
    new_id = C_Movement.list.Max(x => x.id) + 1;

Language Integrated Query, Learn what LINQ is, where you can explore LINQ syntax on your own, and how LINQ makes it Duration: 5:01 Posted: Jan 6, 2020 The LINQ is taking visitors to thrilling new heights with two exciting experiences. Ride on the world’s tallest observation wheel, the High Roller, or soar above the LINQ Promenade on FLY LINQ Zipline.

Try this

    public static class LinqExtensions
    {
        public static TValue Max<TSource, TValue>(this IEnumerable<TSource> source, Func<TSource, TValue> selector, TValue defaultValueIfEmpty)
            where TValue : IComparable
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (selector == null)
                throw new ArgumentNullException(nameof(selector));
            TValue sum;
            using (IEnumerator<TSource> enumerator = source.GetEnumerator())
            {
                if (!enumerator.MoveNext())
                    return defaultValueIfEmpty;
                sum = selector(enumerator.Current);
                while (enumerator.MoveNext())
                {
                    var num2 = selector(enumerator.Current);
                    if (num2.CompareTo(sum) > 0)
                        sum = num2;
                }
            }
            return sum;
        }

        public static TSource Max<TSource>(this IEnumerable<TSource> source, TSource defaultValueIfEmpty)
            where TSource : IComparable
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            TSource sum;
            using (IEnumerator<TSource> enumerator = source.GetEnumerator())
            {
                if (!enumerator.MoveNext())
                    return defaultValueIfEmpty;
                sum = enumerator.Current;
                while (enumerator.MoveNext())
                {
                    var num2 = enumerator.Current;
                    if (num2.CompareTo(sum) > 0)
                        sum = num2;
                }
            }
            return sum;
        }

    }

LINQ: Home, Review extension methods from the System.Linq namespace. Learn to write queries directly in programs. LINQ solutions connect your departments, helping to eliminate manual errors, and increase transparency and productivity. Plus, parents and students will love staying connected to the school with the automated communication tools and apps. Keep Your Work Compliant

LINQ - Overview, LINQ stands for Language Integrated Query. LINQ is a data querying API that provides querying capabilities to .NET languages with a syntax� Language Integrated Query (LINQ, pronounced "link") is a Microsoft.NET Framework component that adds native data querying capabilities to.NET languages, originally released as a major part of.NET Framework 3.5 in 2007.

Introduction to Language Integrated Query (LINQ), Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. Please consider� Linq to SQL is a fairly bare-bones Object-Relational Mapper (ORM) for an MSSQL Server Database. The JSON.NET library provides efficient JSON Document traversal via LINQ. Furthermore, if there isn’t a library which does what you need, you can also write your own LINQ Provider! Why Use the Query Syntax?

C# LINQ, LINQ Brings Together People and Technology Our vision is to continually improve K-12 education through our technology and our people. Informed by over 3 decades of experience, our school management software has been carefully crafted to accomplish the single goal of helping school districts simply run better.

Comments
  • How can it return null when it's returning an integer?
  • For future reference, the "? :" structure is actually called the conditional operator (in MSDN docs), but most folks call it the ternary operator. :)
  • It's worth noting that only Max() on collections of nullable types returns null for empty sequence while Max() in general throws exception.
  • you don't need an else here since you've already set it to 0
  • That's true, I guess I'm anal about certain things. Bad habits die hard!
  • The major problem with this version is that it will double enumerate the iterator. The "Any" will be the first iteration and the "Max" will be the second. This implementation should be avoided.
  • The generic type constraint where TValue : IComparable defeats the purpose of defaultValueIfEmpty because a nullable type doesn't implement IComparable. Besides that, (1) it's always useful when posting code exceeding a couple of lines to add some explanation, and (2) "Try this" isn't really an answer.
  • I meant Nullable<T>. My first effort trying your code failed with int?. About an explanation. Code itself may be easy to understand, but the process leading to that specific solution is at least as interesting.
  • It's the exact same Microsoft source code of Max augmented to have a default value.
  • github.com/Microsoft/referencesource/blob/master/System.Core/… Line 1879. It uses a Comparer<TSource>.Default which implements IComparer.
  • That's not the same as a generic type constraint. Comparer<int?>.Default is an object comparing two int? instances. An int? itself is not IComparable, rendering your function useless for Nullable<T> types (and anything else that doesn't implement IComparable).