ASP NET从列表中选择对象

时间:2014-11-08 11:38:40

标签: c# asp.net asp.net-mvc

我是ASP NET的初学者而且我不知道如何从列表中选择对象例如我的模型中有静态数据:

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;
        }
    }

我有一个发送用户ID的ajax请求。为此,我在控制器中有actionresult:

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 个答案:

答案 0 :(得分:2)

这应该做:

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

它正在利用LINQ,这对查询对象非常有用。

答案 1 :(得分:1)

如果您想获得一位用户,可以使用WhereFirstOrDefault

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