CoolArchTek
CoolArchTek

Reputation: 3839

Finding Dictionary values based on object/type members

I have dictionary defined like below,

Dictionary<string, SampleObject> test = new Dictionary<string, SampleObject>();

test.Add("A", null);

test.Add("B", new SampleObject()
{
    ID = "1",
    Value1 = "BBBBB1",
    Value2 = "BBBBB2"
});

test.Add("C", new SampleObject()
{
    ID = "1",
    Value1 = "CDCDCD1",
    Value2 = "CDCDCD2"
});

test.Add("D", new SampleObject()
{
    ID = "2",
    Value1 = "XXFFA",
    Value2 = "XXFFB"
});

How do I get list/count where object/type is null?

How do I get list/count where object/type property (ID = 1)?

I tried this and getting an error.

var ones = test.Where(t => t.Value.ID.Equals("1"));

Upvotes: 0

Views: 59

Answers (4)

Wojciech
Wojciech

Reputation: 234

I can see good answers already. Just would like to add that from C# 6.0 you will be able to use Null-Conditional Operator: c# 6.0. And your code will be fine with small modification adding ? where the null appear on value.

var ones = test.Where(t => t.Value?.ID.Equals("1"));

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can get count of null object this way:

var ones = test.Where(t => t.Value == null).Count();

and for object with ID equals to 1 :

var ones = test.Where(t => t.Value != null && t.Value.ID == 1).Count();

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

you just need to weed out the nulls first:

var nulls = test.Count(c => c.Value == null);
var ones = test.Count(c => c.Value != null && c.Value.ID == "1");

Upvotes: 1

madd0
madd0

Reputation: 9303

The problem is that the first item that you are adding to your dictionary is null, so when executing the predicate t.Value.ID.Equals("1"), for that value t.Value is null and the error that you are getting is a NullReferenceException.

The code is bascially correct, you could avoid adding null values to your dictionary, or testing for them in your predicate:

var ones = test.Where(t => t.Value != null && t.Value.ID.Equals("1"));

Upvotes: 1

Related Questions