I've currently had to put some data in dictionary, to check whether some of the actual data, match the expected one for some of my tests.
For the task I've created a Dictionary that looked somehow like that:
Dictionary<string, string> dict = new Dictionary<string, string>(){
{a, a},
{b, b},
{c, c}
};
The first that I've tried was to compare the Dictionary Values and Keys in conditional statement like shown below and I was kinda suprised with the false result of this conditional statement:
if(dict.Keys.Equals(dict.Values)) {
///// received false as a result here //////
}
When I then tried the next approach which was to iterate through all of dictionary items and to compare each of their Value Key pairs, it suddenly resulted in giving me the expected (true) result for all items of Dictionary:
foreach (var item in dict) {
if (item.Key.Equals(item.Value))
{
///// received true as a result /////
}
else { other code here }
}
Why did I get the false result for the first approach described?
You expect them both to be an ICollection if you look into the docs.
Have a look in the reference source of the dictionary class.
The Keys and Values Properties are implemented using different collection-types.
// Line 135
public KeyCollection Keys {
get {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
// Line 157
public ValueCollection Values {
get {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
Also if you look into the KeyCollection and ValueCollection Classes, you will notice, that there is no other implementation of the Equals() Method. As those classes don't derive from any other class, you may be sure that dict.Keys.Equals(dict.Values) will call the object.Equals() Method.
This call will obviously return false.
I am new to C# and I have a method that uses removeAll to remove objects from a list but I am not quite sure what the return value is. I have looked around but am struggling to find a definitive answer.
does the method return a value of 1 or 0 based on if an object was removed or does it return the number of objects removed? if it is just returning 1 or 0 how would i go about counting the number of objects that have been removed?
public bool Remove(string name)
{
if (this.list.RemoveAll(x => x.Name.Equals(name)) == 1)
{
return true;
}
return false;
}
According to MSDN for List.RemoveAll()
Return Value Type: System.Int32 The number of elements removed from
the List.
So you just can return this.list.RemoveAll(x => x.Name.Equals(name))
Assuming that list is of type List<string>, note that the data structure can hold duplicates. To account for that, use the fact that the return value is the number of elements removed:
public bool Remove(string name)
{
return this.list.RemoveAll(x => x.Name.Equals(name)) >= 1;
}
I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.
// I have a list, sometimes it doesn't have any data added to it
var myList = new List<object>();
// Expression is always false
if (myList == null)
Console.WriteLine("List is never null");
if (myList[0] == null)
myList.Add("new item");
//Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says "null"
Try the following code:
if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}
A late EDIT because for these checks I now like to use the following solution.
First, add a small reusable extension method called Safe():
public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}
foreach (var item in source)
{
yield return item;
}
}
}
And then, you can do the same like:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.
And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):
if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:
if (list?.Any() != true)
{
// Handle null or empty list
}
Checkout L-Four's answer.
A less-efficient answer:
if(myList.Count == 0){
// nothing is there. Add here
}
Basically new List<T> will not be null but will have no elements. As is noted in the comments, the above will throw an exception if the list is uninstantiated. But as for the snippet in the question, where it is instantiated, the above will work just fine.
If you need to check for null, then it would be:
if(myList != null && myList.Count == 0){
// The list is empty. Add something here
}
Even better would be to use !myList.Any() and as is mentioned in the aforementioned L-Four's answer as short circuiting is faster than linear counting of the elements in the list.
What about using an extension method?
public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
if (source != null && source.Any())
return true;
else
return false;
}
An easy way to combine myList == null || myList.Count == 0 would be to use the null coalescing operator ??:
if ((myList?.Count ?? 0) == 0) {
//My list is null or empty
}
if (myList?.Any() == true)
{
...
}
I find this the most convenient way. '== true' checks the value of the nullable bool implied by '?.Any()
Assuming that the list is never null, the following code checks if the list is empty and adds a new element if empty:
if (!myList.Any())
{
myList.Add("new item");
}
If it is possible that the list is null, a null check must be added before the Any() condition:
if (myList != null && !myList.Any())
{
myList.Add("new item");
}
In my opinion, using Any() instead of Count == 0 is preferable since it better expresses the intent of checking if the list has any element or is empty.
However, considering the performance of each approach, using Any() is generally slower than Count.
I was wondering nobody suggested to create own extension method more readable name for OP's case.
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
{
return true;
}
return source.Any() == false;
}
The IsNullOrEmpty() extension method is a very elegant and human-readable way of implementing this, so I decided to use it. However, you can achieve the same thing without extension methods, too.
Let's say we have an object named list of type List<T> (e.g. List<string>). If you want to know whether the list has items, you can say:
list?.Count > 0 // List<T> has items
This will return false for an empty list and also if the list itself is a null object, true otherwise.
So the only thing you need to do if you want to check whether the list doesn't have any items is to invert the above expression:
!(list?.Count > 0) // List<T> is null or empty
This will return true for an empty list and also if the list itself is a null object, false otherwise. Exactly what you expect from an IsNullOrEmpty evaluation. Just a little cryptic!
As List<T> implements IEnumerable<T>, you can implement the same thing less specific, but this will possibly make the evaluation slower:
list?.Any() != true // IEnumerable<T> is null or empty
Your List has no items, that's why access to non-existing 0th item
myList[0] == null
throws Index was out of range exception; when you want to access n-th item check
if (myList.Count > n)
DoSomething(myList[n])
in your case
if (myList.Count > 0) // <- You can safely get 0-th item
if (myList[0] == null)
myList.Add("new item");
myList[0] gets the first item in the list. Since the list is empty there is no item to get and you get the IndexOutOfRangeException instead.
As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list (myList.Count) or use the LINQ method .Any() which will return true if there are any elements in the list.
Most answers here focused on how to check if a collection is Empty or Null which was quite straight forward as demonstrated by them.
Like many people here, I was also wondering why does not Microsoft itself provide such a basic feature which is already provided for String type (String.IsNullOrEmpty())? Then I encountered this guideline from Microsoft where it says:
X DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.
The general rule is that null and empty (0 item) collections or arrays
should be treated the same.
So, ideally you should never have a collection which is null if you follow this guideline from Microsoft. And that will help you to remove unnecessary null checking which ultimately will make your code more readable. In this case, someone just need to check : myList.Any() to find out whether there is any element present in the list.
Hope this explanation will help someone who will face same problem in future and wondering why isn't there any such feature to check whether a collection is null or empty.
You can check the list is empty or not in multiple ways
1)Checklist is null and then check count is greater than zero like below:-
if (myList != null && myList.Count > 0)
{
//List has more than one record.
}
2)Checklist null and count greater than zero using LINQ query like below:-
if (myList?.Any() == true)
{
//List has more than one record.
}
List in c# has a Count property. It can be used like so:
if(myList == null) // Checks if list is null
// Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
myList.Add("new item");
else // List is valid and has something in it
// You could access the element in the list if you wanted
If you want a single line condition that checks both null and empty, you can use
if (list == null ? true : (!list.Any()))
This will work in older framework versions where the null-conditional operator is not available.
Try and use:
if(myList.Any())
{
}
Note: this assmumes myList is not null.
You can use Count property of List in c#
please find below code which checks list empty and null both in a single condition
if(myList == null || myList.Count == 0)
{
//Do Something
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return !(items?.Any() ?? false);
}
This extension method helps you determine if a list is either null or empty.
It can be used as follows:
using System;
using System.Linq;
using System.Collections.Generic;
public static class IEnumerableExtensions
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return !(items?.Any() ?? false);
}
}
public class Program
{
public static void Main()
{
List<string> test1 = null;;
Console.WriteLine($"List 1 is empty: {test1.IsNullOrEmpty()}");
//Output: List 1 is empty: True
var test2 = new System.Collections.Generic.List<string>();
System.Console.WriteLine($"List 2 is empty: {test2.IsNullOrEmpty()}");
//Output: List 2 is empty: True
var test3 = new System.Collections.Generic.List<string>();
test3.Add("test");
System.Console.WriteLine($"List 3 is empty: {test3.IsNullOrEmpty()}");
//Output: List 3 is empty: False
}
}
We can validate like below with Extension methods. I use them for all of my projects.
var myList = new List<string>();
if(!myList.HasValue())
{
Console.WriteLine("List has value(s)");
}
if(!myList.HasValue())
{
Console.WriteLine("List is either null or empty");
}
if(myList.HasValue())
{
if (!myList[0].HasValue())
{
myList.Add("new item");
}
}
/// <summary>
/// This Method will return True if List is Not Null and it's items count>0
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns>Bool</returns>
public static bool HasValue<T>(this IEnumerable<T> items)
{
if (items != null)
{
if (items.Count() > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// This Method will return True if List is Not Null and it's items count>0
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static bool HasValue<T>(this List<T> items)
{
if (items != null)
{
if (items.Count() > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// This method returns true if string not null and not empty
/// </summary>
/// <param name="ObjectValue"></param>
/// <returns>bool</returns>
public static bool HasValue(this string ObjectValue)
{
if (ObjectValue != null)
{
if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
{
return true;
}
}
return false;
}
We can add an extension to create an empty list
public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
{
if (obj == null)
return new List<T>();
else
return obj;
}
And use like this
foreach (model in models.Nullable())
{
....
}
I personally create an extension method for the IEnumerable class which I call IsNullOrEmpty(). Because it applies to all implementations of IEnumerable, it works for a List, but also for a String, IReadOnlyList, etc.
My implementation is simply this:
public static class ExtensionMethods
{
public static bool IsNullOrEmpty(this IEnumerable enumerable)
{
if (enumerable is null) return true;
foreach (var element in enumerable)
{
//If we make it here, it means there are elements, and we return false
return false;
}
return true;
}
}
I can then use the method on a list as follows:
var myList = new List<object>();
if (myList.IsNullOrEmpty())
{
//Do stuff
}
I just wanted to add an answer here since this is the top hit on Google for checking if a List is null or empty. For me .Any is not recognized. If you want to check without creating an extension method you can do it like this which is pretty simple:
//Check that list is NOT null or empty.
if (myList != null && myList.Count > 0)
{
//then proceed to do something, no issues here.
}
//Check if list is null or empty.
if (myList == null || myList.Count == 0)
{
//error handling here for null or empty list
}
//checking with if/else-if/else
if (myList == null)
{
//null handling
}
else if(myList.Count == 0)
{
//handle zero count
}
else
{
//no issues here, proceed
}
If there is a possibility the list could be null then you must check for null first - if you try to check the count first and the list happens to be null then it will throw an error. && and || are short-circuit operators, so the second condition is only evaluated if the first is not satisfied.
You can add this IEnumerable extension method that returns true if the source sequence either contains any elements and is not null. Otherwise returns false.
public static class IEnumerableExtensions
{
public static bool IsNotNullNorEmpty<T>(this IEnumerable<T> source)
=> source?.Any() ?? false;
}
Because you initialize myList with 'new', the list itself will never be null.
But it can be filled with 'null' values.
In that case .Count > 0 and .Any() will be true. You can check this with the .All(s => s == null)
var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))
This is able to solve your problem
`if(list.Length > 0){
}`
I have the following method which returns an IEnumerable of type T. The implementation of the method is not important, apart from the yield return to lazy load the IEnumerable. This is necessary as the result could have millions of items.
public IEnumerable<T> Parse()
{
foreach(...)
{
yield return parsedObject;
}
}
Problem:
I have the following property which can be used to determine if the IEnumerable will have any items:
public bool HasItems
{
get
{
return Parse().Take(1).SingleOrDefault() != null;
}
}
Is there perhaps a better way to do this?
IEnumerable.Any() will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.
Similar to Howto: Count the items from a IEnumerable<T> without iterating? an Enumerable is meant to be a lazy, read-forward "list", and like quantum mechanics the act of investigating it alters its state.
See confirmation: https://dotnetfiddle.net/GPMVXH
var sideeffect = 0;
var enumerable = Enumerable.Range(1, 10).Select(i => {
// show how many times it happens
sideeffect++;
return i;
});
// will 'enumerate' one item!
if(enumerable.Any()) Console.WriteLine("There are items in the list; sideeffect={0}", sideeffect);
enumerable.Any() is the cleanest way to check if there are any items in the list. You could try casting to something not lazy, like if(null != (list = enumerable as ICollection<T>) && list.Any()) return true.
Or, your scenario may permit using an Enumerator and making a preliminary check before enumerating:
var e = enumerable.GetEnumerator();
// check first
if(!e.MoveNext()) return;
// do some stuff, then enumerate the list
do {
actOn(e.Current); // do stuff with the current item
} while(e.MoveNext()); // stop when we don't have anything else
The best way to answer this question, and to clear all doubts, is to see what the 'Any' function does.
public static bool Any<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) return true;
}
return false;
}
https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs
If I want to perform actions such as .Where(...) or .Max(...), I need to make sure the list is not null and has a count greater than zero. Besides doing something such as the following everytime I want to use the list:
if(mylist != null && mylist.Count > 0)
{...}
is there something more inline or lambda like technique that I can use? Or another more compressed technique?
public static class LinqExtensions
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return items == null || !items.Any();
}
}
You can then do something like
if (!myList.IsNullOrEmpty())
....
My general preference is to have empty list instances, instead of null list variables. However, not everyone can cajole their co-workers into this arrangment. You can protect yourself from null list variables using this extension method.
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Called by:
Customers result = myList.EmptyIfNull().Where(c => c.Name == "Bob");
Most linq methods work on empty collections. Two methods that don't are Min and Max. Generally, I call these methods against an IGrouping. Most IGrouping implementations have at least one element (for example, IGroupings generated by GroupBy or ToLookup). For other cases, you can use Enumerable.DefaultIfEmpty.
int result = myList.EmptyIfNull().Select(c => c.FavoriteNumber).DefaultIfEmpty().Max();
Don't let the list be null
Ensure the object is always in a valid state. By ensuring the list is never null, you never have to check that the list is null.
public class MyClass
{
private readonly IEnumerable<int> ints;
public MyClass(IEnumerable<int> ints)
{
this.ints = ints;
}
public IEnumerable<int> IntsGreaterThan5()
{
return this.ints.Where(x => x > 5);
}
}
Even if this list were empty, you'd still get a valid IEnumerable<int> back.
Max and Min overloads with Nullable types
That still doesn't solve the "Max" and "Min" problems though. There's an overload of Max and Min that take selectors. Those selector overloads can return nullable ints, so your max method becomes this:
this.ints.Max(x => new int?(x));
Therefore, you run Max and check to see if you've gotten a null value or an integer back. voila!
Other Options
Custom Extension Methods
You could also write your own extension methods.
public static MinMaxHelper()
{
public static int? MaxOrDefault(IEnumerable<int> ints)
{
if(!ints.Any())
{
return null;
}
return ints.Max();
}
public static int MaxOrDefault(IEnumerable<int> ints, int defaultValue)
{
if(!ints.Any())
{
return defaultValue;
}
return ints.Max();
}
}
Overriding Linq Extension Methods
And finally, remember that the build in Linq extension methods can be overriden with your own extension methods with matching signatures. Therefore, you could write an extension method to replace .Where(...) and .Max(...) to return null (or a default value) instead of throwing an ArgumentNullException if the Enumerable is null.
Use empty collections instead of null collections. Where will work just fine against an empty collection, so you don't need to ensure that Count > 0 before calling it. You can also call Max on an empty collection if you do a bit of gymnastics first.
For IEnumerable<T> use Enumerable.Empty<T>()
For T[] use new T[0]
For List<T> use new List<T>()
You could try myList.Any() instead of .Count, but you'd still need to check for null.
If there is a risk of your list being null you will alway have to check that before calling any of its methods but you could use the Any() method rather than count. This will return true as soon as it counts one item regardless if there is one or more item in the list. This saves iterating over the entire list which is what Count will do:
if(mylist != null && mylist.Any())
{...}
You can use ?? operator which converts null to the value you supply on the right side:
public ProcessList(IEnumerable<int> ints)
{
this.ints = ints ?? new List<int>();
}
By the way: It is not a problem to process an empty list using LINQ.
You don't need to check Count to call Where. Max needs a non-empty list for value types but that can be overcome with an inline cast, eg
int? max = new List<int>().Max(i => (int?)i); // max = null