views:

248

answers:

3

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 "

+3  A: 

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;
Marc Gravell
+1  A: 

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.
BengtBe
you are in error: 'The method 'Single' is not supported by LINQ to Entities. Consider using the method 'First' instead.'
Phsika
@ykaratoprak - that is a bit harsh; you didn't make it obvious that you were using EF. This answer would be fine with many LINQ providers, such as LINQ-to-SQL. I'm giving it +1...
Marc Gravell
A: 

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();

Michael