简体   繁体   中英

Filter data from a collection

I have a collection of a Parent class. Parent class has an ID property and some other class property. So, I would like to fetch those child property values on the basis of the Parent ID . I am able to fetch an item of the collection but I need a single value from that item. Below is my code:

public class Parent
{
    public int Id { get; set; }
    public Child MyChild { get; set; }

}

public class Child
{
    public string abc { get; set; }
    public string xyz { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var d = new List<Parent>();
        d.Add(new Parent
        {
            Id = 1,
            MyChild = new Child()
            {
                xyz = "XYZ one",
                abc = "ABC one"
            }
        });

        d.Add(new Parent
        {
            Id = 2,
            MyChild = new Child()
            {
                xyz = "XYZ two",
                abc = "ABC two"
            }
        });

        for (int i = 1; i < 2; i++)
        {
            var xyzValueOfParentIdOneValue = d.SingleOrDefault(x => x.Id = 1) // Here, I want to get XYZ property value of Parent ID 1.
        }

    }

}

I think you just want to access the MyChild property of the Parent , like:

        var parent = d.SingleOrDefault(x => x.Id == 1);
        var xyz = parent.MyChild.xyz;

You could use this

var xyzValueOfParentIdOneValue = d.SingleOrDefault(x => x.Id == 1)
                                       ?.MyChild
                                       ?.xyz;

if (xyzValueOfParentIdOneValue != null)
{
   ......
}

Or

var foundItem = d.SingleOrDefault(x => x.Id == 1);

if (foundItem != null && foundItem.MyChild != null)
{ 
  var xyzValueOfParentIdOneValue = foundItem.MyChild.xyz;
}

These two above codes are completely similar.

Since you want to return a default value "0" if the Parent Id doesn't exist, you could use

var xyzValueOfParentIdOneValue = d.SingleOrDefault(x => x.Id == idToSearch)?
                                  .MyChild?
                                  .xyz ?? "0";

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