简体   繁体   中英

Remove all null entries from generic list of Object

This one should be easy, but seems to be eluding me.

Given this variable: (which contains ~30 records)

var seriesData = new List<List<object>>();

How do I loop through every record, and omit any record that contains a null, anywhere inside?

Typically, each list inside will look like one of the following:

["02/16/2019", 5, 7, 10]
["02/17/2019", 3, 15, 2]

and sometimes:

["02/18/2019", 5, {null}, 10]

This is what I have tried, but, it's not working:

foreach (List<object> row in seriesData)
{
    if (row.Contains(null)) seriesData.Remove(row);
}

The result I'm ending up with is completely empty?

您可以使用RemoveAll接受谓词:

seriesData.RemoveAll(row => row.Any(x => x == null))

If you can use LINQ, this should be easy:

seriesData = seriesData
    // filter the lists (x) where all items in them (y) are not null
    .Where(x => x.All(y => y != null))
    // and get the result
    .ToList();

Without LinQ, you may do something like this:

int i = 0;
while (i < seriesData.Count)
{
    if (seriesData[i].Contains(null))
    {
        seriesData.RemoveAt(i);
    } else {
        i++;
    }
}

This may very well be the most performant solution and not require LinQ if you don't use it already. If, on the other hand, you already use LinQ, then style may be more important than performance.

As an exercise, I write a version that changes the order of entries but has a lower complexity. As stated by @Lee, the above code may have an O(n^2) complexity. Here is another version, maybe some benchmarking if performance is really important would help:

int i = 0, last;
while (i < seriesData.Count)
{
    if (seriesData[i].Contains(null))
    {
        last = seriesData.Count - 1;
        seriesData[i] = seriesData[last];
        seriesData.RemoveAt(last);
    } else {
        i++;
    }
}

There are many ways to skin a cat. Here is yet another one that doesn't modify your original list:

var nonulls = seriesData.Where(sd => !sd.Any(o => o == null));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM