0

I'm beginner in ASP NET and I don't know how to select object from list for example I have static data in my model:

namespace ProjectMVC.Models
{
    public class Initializer
    {
       
        public List<Profile> GetProfiles()
        {
            var profile = new List<Profile>(){
                new Profile {
                    Id = 2,
                    Name = "Henrik Crawford",
                    SportType = "Спортсмен",
                    Location = "Украина, Кременчуг"
                },
                new Profile {
                    Id = 3,
                    Name = "Diane McCartney",
                    SportType = "Спортсмен",
                    Location = "Украина, Кременчуг"
                },
                new Profile {
                    Id = 4,
                    Name = "William Jenkins",
                    SportType = "Спортсмен",
                    Location = "Украина, Кременчуг"
                },
            };

            return profile;
        }
    }

And I have ajax request which send an Id of user. For this I have actionresult in controller:

namespace ProjectMVC.Controllers
{
    public class HomeController : Controller
    {
        private readonly Initializer init = new Initializer();

       public ActionResult AddUserAjax(int UserId)
        {
          List<Profile> SomeList = init.GetProfiles();

// here I want to select and return user from list , where UserId == Id from list in model

           }
}

2 Answers 2

2

This should do:

var user = SomeList.FirstOrDefault(u => u.Id == UserId)

It's utilising LINQ which is very powerful for querying objects.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just use Where or FirstOrDefault if you want to get one user:

var user = SomeList.FirstOrDefault(u => u.Id == UserId);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.