A Shortcut for c# null and Any() checks [duplicate] - c#

This question already has answers here:
How to check if IEnumerable is null or empty?
(23 answers)
Closed 7 years ago.
Often in C# I have to do this
if(x.Items!=null && x.Items.Any())
{ .... }
Is there a short cut on a collection ?

In C# 6, you'll be able to write:
if (x.Items?.Any() == true)
Before that, you could always write your own extensions method:
public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
return source != null && source.Any();
}
Then just use:
if (x.NotNullOrEmpty())
Change the name to suit your tastes, e.g. NullSafeAny might be more to your liking - but I'd definitely make it clear in the name that it's a valid call even if x is null.

I also do a check on items of the list to assure the list not just contains all null objects; so as enhancement to Jon Skeet answer:
public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
return source != null && !source.All(x => x == null);
}

Related

How can i validate if List<int> is empty? [duplicate]

This question already has answers here:
Check if list is empty in C#
(8 answers)
Closed 3 years ago.
This is my Code:
public int PostCanal(List<int> listchannel) {
if (listchannel == null || listchannel.Contains(0))
{
listchannel.Add(1);
}
This list has values coming from a checkbox menu. So, if the user uncheck all the options I want to still using "1" as default value.
On this case, the listchannel List<int> is arriving with [0] value. However the if condition is skipped.
Any idea? Also tried .Equals Method.
You could use Any Or Count to check if the list is empty or not, like the following code :
if(listchannel == null || !listchannel.Any())
{
}
//Or
if(listchannel == null || listchannel.Count == 0)
{
}
I hope you find this helpful.

Refactor method (C#) [duplicate]

This question already has answers here:
Simply check for multiple statements C#
(2 answers)
C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]
(2 answers)
Closed 3 years ago.
I have got method:
private bool MyMethod(PlantType plantType)
{
return plantType.PlantMoveType == PlantMoveType.PlantReady
|| plantType.PlantMoveType == PlantMoveType.PlantRelase
}
Can I write it into other way? Maybe with LINQ?
One way is to put the enum values that you want to check against into an array, and call Contains.
return new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
If you are using C# 7 or later, you can also write the method as expression-bodied:
private bool MyMethod(PlantType plantType) =>
new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
Well a small simplification would be to pass the type (enum?) of the property PlantMoveType instead of PlantType as the parameter.
Beyond that, you could declare the types to check for as e.g. an array. In case you'd like to reuse that array, you can also declare it outside the scope of the method:
private static PlantMoveType[] _plantStates =
new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};
private bool MyMethod(PlantMoveType plantMoveType)
{
return _plantStates.Contains(plantMoveType);
}

Contains function for C# (Linked list) comparing issue [duplicate]

This question already has answers here:
C# difference between == and Equals()
(20 answers)
Are string.Equals() and == operator really same? [duplicate]
(8 answers)
Closed 5 years ago.
I'm writing a simple contains function which accepts a value and checks if it exists in the linked list. Returns a bool. However, when temp.Data is the same as data, as checked through debugging, it still proceeds to enter the while statement and cycle through the list, as if they are not equal. I have found a solution, by using toString() on all values. So I have to compare temp.Data.ToString() and data.ToString(). Then it works...I am new to C#, I haven't used the Object keyword much. I'm wondering if it's something to do with that? So my function works with my quick fix but I'm trying to understand why...thanks!
public bool Contains(Object data)
{
Node temp = head;
while((temp.Data != data) && (temp.Next != null))
{
temp = temp.Next;
}
//Rest of code

Is there any way to check for string either it is null or blank? [duplicate]

This question already has answers here:
Easier way of writing null or empty?
(7 answers)
Closed 9 years ago.
Is there any way to check for string either it is null or blank("") in c#?
Currently I have to check two conditions first for null and other for blank value
if(val == "" || val == null)
{
return true;
}
You can use String.IsNullOrEmpty() method which checks for string references that are null or have no data:
if(String.IsNullOrEmpty(val))
{
return true;
}
There is also a method String.IsNullOrWhitespace() which indicates whether a specified string is null, empty, or consists only of white-space characters.
if(String.IsNullOrWhitespace(val))
{
return true;
}
The above is a shortcut for the following code:
if(String.IsNullOrEmpty(val) || val.Trim().Length == 0)
{
return true;
}
You can use String.IsNullOrEmpty method.
Indicates whether the specified string is null or an empty string.
if(String.IsNullOrEmpty(val))
{
return true;
}
There is easiest and simple way.
if (string.IsNullOrEmpty("Val")) //This condition comparing both NULL and EMPTY also
{
}
.Net has provided default function for this purpose you should use like this.
if (string.IsNullOrEmpty("any string"))
{
}
You can use String.IsNullOrEMpty.

What is C# equivalent for the Java Enumeration type? Refer to the code below [duplicate]

This question already has an answer here:
How to translate a Java Enumeration to C#?
(1 answer)
Closed 9 years ago.
public Enumeration getLogEntries(String header)
{
return log != null ? ((Vector)log.get(header)).elements() : null;
//log is a hashtable
//
}
This what I have tried in C#, but it's not complete:
public IEnumerator getLogEntries(string header)
{
return log.Keys.GetEnumerator(); //Something is missing here!
//log is Dictionary<string,List<string>>()
}
Don't return the IEnumerator, return the IEnumerable:
public IEnumerable<string> GetLogEntries(string header)
{
return log != null && log.ContainsKey(header) ? log[header] : Enumerable.Empty<string>();
}
Then you iterate over it:
foreach(string entries in GetLogEntries("someKey"))
{
//do something
}
This also has the advantage of being strongly typed.
There are also IList<string> and ICollection<string>. depending on what you want to do with your data and if you plan on .Adding to them.
The Enumerable static class can be found in the System.Linq namespace, if you never heard of linq before, LINQ Query Expressions (C# Programming Guide) is a good read. For me, LINQ changed the way I look at sequences.
IEnumerable is (roughly) equivalent to Iterable in Java, similarly IEnumerator is equivalent to Iterator.
The following is an equivalent C# version of your method:
public IEnumerable<string> GetLogEntries(string header)
{
if (log != null && log.ContainsKey(header))
{
return log[header];
}
return null;
}
As an aside C# uses Pascal case for method name as opposed to Java's camel case.

Categories