Home > Blockchain >  How to only return specific object list base on the condition
How to only return specific object list base on the condition

Time:06-14

I want to add a condition to for returning selected object list. If the condition is met, it will not return the an item if its category is for this example, category is 3.

This is the query:

var objectQuery = query
    .ToList()
    .Select(a => new
    {
        a.Id,
        ObjectDetails = (new ObjectClass[] { })
            .Concat(...)
            .Concat(...)
            .Distinct()
            .Select(f => new
            {
                f.ObjectDetails.Id,
                f.ObjectDetails.Name,
                f.ObjectDetails.DisplayName,
                category = (int)f.ObjectDetails.Category,
                f.ObjectDetails.IsArchived,
            })
    });

return objectQuery.ToList().FirstOrDefault();

i want to add a condition like this where if it met the condition, it will remove all items with category 3 and returns all the item if not, but i dont know how to properly implement it:

if(condition a)
    return objectQuery.Select(...Where(category != 3)).ToList().FirstOrDefault();
else
    return objectQuery.ToList().FirstOrDefault();

this is the return output:

{
  "objectQuery": {
    "id": 1198,
    "ObjectDetails": [
      {
        "id": 1,
        "name": "name one",
        "displayName": "NAME 1",
        "Category": 1,
      },
      {
        "id": 2,
        "name": "name two",
        "displayName": "NAME 2",
        "Category": 1,
      },
      {
        "id": 3,
        "name": "name three",
        "displayName": "NAME 3",
        "Category": 2,
      },
      {
        "id": 4,
        "name": "name four",
        "displayName": "NAME 4",
        "Category": 2,
      },
      {
        "id": 5,
        "name": "name five",
        "displayName": "NAME 5",
        "Category": 3,
      },
      {
        "id": 6,
        "name": "name six",
        "displayName": "NAME 6",
        "Category": 1,
      },
      {
        "id": 7,
        "name": "name seven",
        "displayName": "NAME 7",
        "Category": 1,
      }
    ]
  }
}

CodePudding user response:

If I get your question properly then you'll need something like this:

var objectQuery = query
    .ToList()
    .Select(a => new
    {
        a.Id,
        ObjectDetails = (new ObjectClass[] { })
            .Concat(...)
            .Concat(...)
            .Distinct()
            .Select(f => new
            {
                f.ObjectDetails.Id,
                f.ObjectDetails.Name,
                f.ObjectDetails.DisplayName,
                category = (int)f.ObjectDetails.Category,
                f.ObjectDetails.IsArchived,
            })
            .Where(f => !condition || f.category != 3)
    });

return objectQuery.ToList().FirstOrDefault();
  • Related