Home > Enterprise >  How can i get specific item in a list using LINQ
How can i get specific item in a list using LINQ

Time:09-30

So I am learning the basics of LINQ and I´m haveing a little trouble. How can I get the interval under entry name and exit name?? I'm having a hard time to solve this. this is the code

  List<list> list = new List<list>();
        station1 = new list()
        {
            no = 1,
            interval = 0,
            name = "name1",
            
        };
        station2 = new list()
        {
            no = 2,
            interval = 1,
            name = "name2",
        };
       station3 = new list()
        {
            no= 3,
            interval = 2,
            name = "name3",
        };
       station4 = new list()
        {
            no = 4,
            interval = 1,
            name = "name4",
        };
       station5 = new list()
        {
            no = 5,
            interval = 1,
            name = "name5",
        };

for example I enter the entry station and exit station (name1, name5) I want to add those interval inside the station under name1 and name5.

so the process will be output = name2.interval = 1 name3.interval = 2 name4.interval = 1 ;

total interval = 4

What I tried is, which is wrong and I am stuck:

    interval = list.GetRange(entry, exit);

This only gives me the interval of entry so I need to add a filter. Been trying this and that with no luck. If anyone could give me more hints or be of some assistance would be greatly appreciated

CodePudding user response:

I suggest using Skip and Take:

int total = list
  .OrderBy(item => item.no)                // if stations are not ordered  
  .SkipWhile(item => item.name != "name1") // skip before 1st station
  .Skip(1)                                 // skip 1st station
  .TakeWhile(item => item.name != "name5") // take up to the last station
  .Sum(item => item.interval);             // sum intervals

CodePudding user response:

First, you'd have to get the no of stations with "name1" and "name5". After that, you can get the total with a LINQ query like this:

var no1 = list.First(x => x.name == "name1").no;
var no5 = list.First(x => x.name == "name5").no;
var total = list
  .Where(x => x.no > no1 && x.no < no5)
  .Sum(x => x.interval);

This sample assumes that the stations exist. After getting the no of the stations it filters the list for items with a no between the stations and afterwards builds the sum of the interval field for these items.

In addition, it iterates the list several times. If you want to find the stations by name more efficiently, you could change your list to a Dictionary<string, list> where name is the key and the item is the value. Then you can simply look the items up by name and iterate the list only once. In memory with a limited number of items, the difference will not be too big between the list and the dictionary.

  • Related