user6922053
user6922053

Reputation:

C# how to take specific objects from ilist

i made a list of movies depending on age. If you input your age to be 18+ you are able to see the whole list. if your age is less you get to see a reduced list depending on which ones are for your age.

I made an ilist with the movie names but don't know how to pull out specific movies from the list when showing it.

Here is my code so far:

Console.Write("Hi, if you wish to see a movie please enter your age: ");

string AgeAsAString = Console.ReadLine();
int Age = (int)Convert.ToInt32(AgeAsAString);
List<String> ilist = new List<String>();
ilist.Add("Made in Daghenham");
ilist.Add("Buried");
ilist.Add("Despicable Me");
ilist.Add("The Other Guys");
ilist.Add("Takers");
string combindedString = string.Join(",", ilist);

{ if (Age >= 18)
        Console.Write(combindedString);
    else
        if (Age < 18)
        Console.Write()


        Console.ReadKey();

I can't seem to find a simple answer to it and i'm just starting with this whole coding world. Thanks for the help!

Upvotes: 0

Views: 261

Answers (2)

Swagata Prateek
Swagata Prateek

Reputation: 1086

May be you are looking for a class that holds the movie info you need

class Movie
{
    public string Name { get; set; }
    public int AgeRestriction { get; set; }
}

And then you populate a list based off that class and return results the way you want

        Console.Write("Hi, if you wish to see a movie please enter your age: ");

        string AgeAsAString = Console.ReadLine();
        int Age = (int) Convert.ToInt32(AgeAsAString);

        List<Movie> ilist = new List<Movie>();

        ilist.Add(new Movie()
        {
            Name = "Buried",
            AgeRestriction = 18
        });

        ilist.Add(new Movie()
        {
            Name = "Despicable Me",
            AgeRestriction = 10
        });

        if (Age >= 18)
            return string.Join(",", ilist.Select(x => x.Name));
        else
            return string.Join(",", ilist.Where(x => x.AgeRestriction <= Age));

        Console.ReadKey();

I assumed you needed the result as a conjoined string instead of a List. To filter out a list based on age just use.

ilist.Where(x => x.AgeRestriction <= Age).ToList()

Upvotes: 2

AD.Net
AD.Net

Reputation: 13399

public class Movie
{
   public int MinAge {get;set;}
   public string Name{get;set;}
}
var Movies = new List<Movie>{new Movie{Name = "blahblah", MinAge = 18}};
//create the list of movies with the age information
var filtered = (from m in Movies where m.MinAge >= 18 select m).ToList();

Upvotes: 2

Related Questions