LINQ & .Net Core : Fetch or ignore specific sub array fields. RRS feed

  • Question

  • Let's say I have a large collection, with a sub-array. How do I fetch certain fields from the collection?. I can use projection to fetch or exclude first level fields. Not sure how to do it for the second level, especially using LINQ.

    name: "collection 1"
    properties: "Some properties."
    "contacts": [
          "id": {  },
          "function": "f1",
          "firstname": "Joe",
          "lastname": "Dove",
          "addresses": [
                "Tag" : "Addr 1"
              "street": " street 1",
              "zipcode": "1111",
                "Tag" : "Addr 2"
              "street": " street 2",
              "zipcode": "2222",
    I would like to fetch all the contacts details with the collection apart from addresses. I can write a Builder like

        Builders<T>.Projection.Include(col => new
            {,, col.contacts});
    But I don't know how to include or exclude certain fields from col.contacts. Any suggestions?

    Thanks in advance for going through the rather big post: -)
    Monday, June 4, 2018 8:18 AM


All replies

  • Maybe like this:

    Builders<T>.Projection.Include(col => new {,, contacts = col.contacts.Select(c => new {, c.firstname, c.addresses} });

    Monday, June 4, 2018 4:13 PM
  • Thank you, Viorel looks good. I do have to check it though, my concern is if the second new{} needs to exist as a constructor in the contacts.cs.  

    Initially I have solved it by, 

     Builders<T>.Projection.Include(col => new
            {,, col.contacts[-1].firstname });

    But now I have changed the structure of the collection ( Not due to this). I thank you again for taking time and suggesting me the solution. Cheers !!

    • Edited by Novice_GL Thursday, June 7, 2018 12:43 PM
    Thursday, June 7, 2018 12:43 PM