简体   繁体   中英

Modify linq query how to?

How can i shorter below codes than before? i need short and simple method: i dont want to use foreach loop because i have one value.

  public partial class Test : System.Web.UI.Page
    {
        StaffManagementEntities staffContext;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadStaffPersonel();
            }
        }

        void LoadStaffPersonel()
        {
            int selectedDepartman = Convert.ToInt32(Request.QueryString["SelectedDepartmanID"]);
            string name="";
            using (staffContext = new StaffManagementEntities())
            {

                var DepartmanName = from d in staffContext.Departman
                                    where d.ID == selectedDepartman
                                    select d;
                foreach (Departman d in DepartmanName)
                {
                    name = d.Name;
                }

                ObjectResult<StaffsPersonel> personalData = staffContext.GetPersonelData(name);
                gvPersonel.DataSource = personalData;
                gvPersonel.DataBind();

            }
        }

    }

How to use string value instead of " var DepartmanName "

Something like:

string name = (from d in staffContext.Departman
               where d.ID == selectedDepartman
               select d.Name).First();

or:

string name = staffContext.Departman.Where(d=>d.ID == selectedDepartman)
                  .First().Name;

Is this what you are trying to do?

string name = (from d in staffContext.Departman
                                where d.ID == selectedDepartman
                                select d.Name).SingleOrDefault();

The SingleOrDefault will return the name or null if the department does not exit.

Update:

  • Seems like you at the moment need to use the First method as ykaratoprak commented. But according to this post the Single/SingleOrDefault will be added in Entity Framework 4.0.

You can use "FirstOrDefault" which is available in the current 3.5 framework. I think it may have been included with 3.0, but I'm not certain. I think it will return null (as opposed to an empty string) if the item isn't found....but you'll want to double check that.

string name = (from d in staffContext.Departman where d.ID == selectedDepartman select d.Name).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM