How to determine if a list of string contains null or empty elements
keys.contains(null) || keys.contains("")
Doesn't throw any runtime exceptions and results true
if your list has either null (or) empty String.
How do I check if the list contains empty elements?
With bool([''])
you're checking if the list ['']
has any contents, which it does, the contents just happen to be the empty string ''
.
If you want to check whether all the elements in the list aren't 'empty' (so if the list contains the string ''
it will return False
) you can use the built-in function all()
:
all(v for v in l)
This takes every element v
in list l
and checks if it has a True
value; if all elements do it returns True
if at least one doesn't it returns False
. As an example:
l = ''.split(',')
all(v for v in l)
Out[75]: False
You can substitute this with any()
to perform a partial check and see if any of the items in the list l
have a value of True
.
A more comprehensive example* with both uses:
l = [1, 2, 3, '']
all(l)
# '' doesn't have a True value
Out[82]: False
# 1, 2, 3 have a True value
any(l)
Out[83]: True
*As @ShadowRanger pointed out in the comments, the same exact thing can be done with all(l)
or any(l)
since they both just accept an iterable in the end.
Checking for empty or null List<string>
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");
}
c# check if list contains a null element and do not list entire line in a for statement
Since you would only know at runtime, you can't use an array. Use the List<string>
directly instead.
Now, make a method:
void AddIfNotNull(List<string> list, string prefix, object suffix)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
if (suffix == null)
{
return;
}
list.Add(prefix + suffix);
}
I suppose we we can create a generic version of that. However, I'm not going to bother (if you know the type, you figure that out). Instead, I will make a version that takes tuples:
void AddIfNotNull(List<string> list, (string prefix, object suffix) line)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
if (line.suffix == null)
{
return;
}
list.Add(line.prefix + line.suffix);
}
Sorry, I meant tuples, plural:
void AddIfNotNull(List<string> list, IEnumerable<(string prefix, object suffix)> lines)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
if (lines == null)
{
throw new ArgumentNullException(nameof(lines));
}
foreach (var (prefix, suffix) in lines)
{
if (suffix == null)
{
continue;
}
list.Add(prefix + suffix);
}
}
Now we can use it like this:
var list = new List<String>();
AddIfNotNull
(
list,
new []
{
("Device State: ", device.State),
("Something", new object()),
("Some other", null),
}
);
I suppose that since you are going to concatenate anyway, you could work with string?
(that is define the tuple type as (string prefix, string? suffix)
), then using .?toString()
would be handy.
Another way you could take this is to not concatenate them until you need to output them. In fact, why a list and not a Dictionary
? Well, that is up to you.
Handling empty string and white-space:
void AddIfNotNull(List<string> list, IEnumerable<(string prefix, string? suffix)> lines)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
if (lines == null)
{
throw new ArgumentNullException(nameof(lines));
}
foreach (var (prefix, suffix) in lines)
{
if (string.IsNullOrWhiteSpace(suffix))
{
continue;
}
list.Add(prefix + suffix);
}
}
Check if arraylist contains only nulls
Generally, no; there is no other way to tell that an arbitrary ArrayList contains ten instances of null
than to loop over it and make sure each element is null
. You can forgo this, of course, if the size() of the list isn't equal to ten.
Python check if list only contains either empty elements or whitespace
Well your whitespace is simply str.isspace(..)
so:
if all('' == s or s.isspace() for s in l):
return True
c# check if list contains an existing element (not null)
Use the linq Any
method:
if (myList.Any(i => i != null))
{
DoSomeThing();
}
Related Topics
Jsonobject.Tostring: How Not to Escape Slashes
How to Trim White Space from All Elements in Array
How to Store a String Longer Than 4000 Characters in an Oracle Database Using Java/Jdbc
Java 8 Streams - How to Merge Elements from the List With the Same Fields to One Element and Sum Up
Mock Objects Created Inside Method Under Test to Verify the Arguments Passed
Extract Text Br Tags in Selenium Java
Iterating Over Two Arrays Simultaneously Using for Each Loop in Java
How to Check a Long for Null in Java
Keycloak - Create Realms/Users/Groups Programmatically
Connection Java - Mysql:Public Key Retrieval Is Not Allowed
Springboot 401 Unauthorized Even With Out Security
Why Is My Spring @Autowired Field Null
How to Make a Jframe Button Open Another Jframe Class in Netbeans
How to Go About Adding an Image into a Java Project With Eclipse
Java 8 Convert Utc Time to Edt/Est So That Date Remains the Same
The Import Android.Support Cannot Be Resolved
Java Sorting a 2D Array Rows into Ascending and Columns into Descending Order