David Fattal
David Fattal

Reputation: 23

how do I ask an if argument on a specific field which in a list of objects that contain a list in c#?

I have a list of objects in which every object is containing a list itself. how do I get the the JellyFishID field or the Amount field for using an IF argument (I'm currently using Foreach):`

 public static List<Report> DataSorted = new List<Report> {
            new Report() { IsGoldUser=true, Date=new DateTime(2016, 3, 12,11, 59, 33), IsBurningWater=true, Type=Type.Shore, ZoneID = 1 ,
                ReportDetails =new List<ReportDetail> { new ReportDetail() { Amount = Amount.Few, Jellyfish = new Jellyfish { JellyfishID = 1, Venom = Venom.Strong } }  }  },
            new Report() { IsGoldUser=true, Date=new DateTime(2016, 3, 12, 11, 59, 33), IsBurningWater=true, Type=Type.Shore, ZoneID = 1 ,
                ReportDetails =new List<ReportDetail> { new ReportDetail() { Amount = Amount.Few, Jellyfish = new Jellyfish { JellyfishID = 1, Venom = Venom.Strong } }  }  },
            new Report() { IsGoldUser=true, Date=new DateTime(2016, 3, 12, 11, 59, 33), IsBurningWater=true, Type=Type.Shore, ZoneID = 1 ,
                ReportDetails =new List<ReportDetail> { new ReportDetail() { Amount = Amount.Few, Jellyfish = new Jellyfish { JellyfishID = 1, Venom = Venom.Strong } }  }  },
            new Report() { IsGoldUser=true, Date=new DateTime(2016, 3, 12, 11, 59, 33), IsBurningWater=true, Type=Type.Shore, ZoneID = 1 ,
                ReportDetails =new List<ReportDetail> { new ReportDetail() { Amount = Amount.Few, Jellyfish = new Jellyfish { JellyfishID = 1, Venom = Venom.Strong } }  }  },

 foreach (var item in DataSorted)
        {

               if (item.ReportDetails....) //???I want here to Make an Argument about The Amount field or the JellyFishID field in the list above....

        }

Upvotes: 0

Views: 46

Answers (1)

ventiseis
ventiseis

Reputation: 3099

You don't describe exactly what you want to check, but with LINQ to Objects you have a lot of possiblities. At first, you need to reference the correct namespace with

using System.Linq;

at the top of your source code file.

Now, if you want to check if any items of your list contains a jellyfish with a given ID, you can use:

if (item.ReportDetails.Any(t => t.Jellyfish.JellyfishID == 1)) //...

Additionally you can have conditions inside a Where-function to filter your list and search only for jellyfish with a few amount:

if (item.ReportDetails.Where(t => t.Amount == Amount.Few).
                       Any(t => t.Jellyfish.JellyfishID == 1)) //...

There is a lot of information avaliable about LINQ, a lot of examples are in the MSDN (for example this intro page), but there are alternatives like this one: 101 Linq examples. It even has a tag on StackOverflow.

Upvotes: 2

Related Questions