Solved

more efficent LINQ statement + how to ignore if a string is empty without writing a load of if statements

Posted on 2011-02-23
9
351 Views
Last Modified: 2012-05-11
hi all,

my code below should explain it all.

its a function to insert and or update data in my company table
is there a more efficent way to do this, if so can someone show me?

also in the update section, is there a method that will ignore updating a field if the string is blank, or do i have to do an if statement for eachone? :S

Thanks
public static void InsertOrUpdateCompanyInfo(string StrID, string StrACK,
            string StrRMID, string StrUser, string StrSec1, string StrSec2, string StrSec3, string StrSec4, string StrSec5,
            string StrCompanyType, string StrOfficeTel, string StrOfficeFax, string StrTrades, string StrCompanyReg,
            string StrCompanyName, string StrAddress1, string StrAddress2, string StrAddress3, string StrPostcode,
            string StrWebsite, string StrYearEstablished, string StrConstructionline, string StrCHAS, string StrNotes,
            string StrLocked)
        {
            using (MiscDataContext dc = new MiscDataContext())
            {
                Table<CompanyInfo> CompanyData = dc.GetTable<CompanyInfo>();
                if (StrID == "")
                {
                    CompanyInfo CData = new CompanyInfo();
                    CData.ACK = Convert.ToInt16(StrACK);
                    CData.RMID = Convert.ToInt16(StrRMID);
                    CData.Sec1 = Convert.ToInt16(StrSec1);
                    CData.Sec2 = Convert.ToInt16(StrSec2);
                    CData.Sec3 = Convert.ToInt16(StrSec3);
                    CData.Sec4 = Convert.ToInt16(StrSec4);
                    CData.Sec5 = Convert.ToInt16(StrSec5);                  
                    CData.CompanyType = StrCompanyType;
                    CData.OfficeTel = StrOfficeTel;
                    CData.OfficeFax = StrOfficeFax;
                    CData.Trades = StrTrades;
                    CData.CompanyReg =StrCompanyReg;
                    CData.CompanyName = StrCompanyName;
                    CData.Address1 = StrAddress1;
                    CData.Address2 = StrAddress2;
                    CData.Address3 = StrAddress3;
                    CData.Postcode = StrPostcode;
                    CData.Website = StrWebsite;
                    CData.YearEstablished = StrYearEstablished;
                    CData.Constructionline = StrConstructionline;
                    CData.CHAS = StrCHAS;
                    CData.Notes = StrNotes;
                    CData.Locked = Convert.ToInt16(StrLocked);
                    CData.DateAdded = DateTime.Now;

                    CompanyData.InsertOnSubmit(CData);
                }
                else
                {
                    int NewStrID = Convert.ToInt16(StrID);
                    CompanyInfo MatchedCompany = CompanyData.SingleOrDefault(c => c.ID == NewStrID);
                    MatchedCompany.ACK = Convert.ToInt16(StrACK);
                    MatchedCompany.RMID = Convert.ToInt16(StrRMID);
                    MatchedCompany.Sec1 = Convert.ToInt16(StrSec1);
                    MatchedCompany.Sec2 = Convert.ToInt16(StrSec2);
                    MatchedCompany.Sec3 = Convert.ToInt16(StrSec3);
                    MatchedCompany.Sec4 = Convert.ToInt16(StrSec4);
                    MatchedCompany.Sec5 = Convert.ToInt16(StrSec5);
                    MatchedCompany.CompanyType = StrCompanyType;
                    MatchedCompany.OfficeTel = StrOfficeTel;
                    MatchedCompany.OfficeFax = StrOfficeFax;
                    MatchedCompany.Trades = StrTrades;
                    MatchedCompany.CompanyReg = StrCompanyReg;
                    MatchedCompany.CompanyName = StrCompanyName;
                    MatchedCompany.Address1 = StrAddress1;
                    MatchedCompany.Address2 = StrAddress2;
                    MatchedCompany.Address3 = StrAddress3;
                    MatchedCompany.Postcode = StrPostcode;
                    MatchedCompany.Website = StrWebsite;
                    MatchedCompany.YearEstablished = StrYearEstablished;
                    MatchedCompany.Constructionline = StrConstructionline;
                    MatchedCompany.CHAS = StrCHAS;
                    MatchedCompany.Notes = StrNotes;
                    MatchedCompany.Locked = Convert.ToInt16(StrLocked);
                    MatchedCompany.DateEdited = DateTime.Now;
                    MatchedCompany.EditedBy = StrUser;
                }
                dc.SubmitChanges();
            }
        }

Open in new window

0
Comment
Question by:awilderbeast
  • 5
  • 3
9 Comments
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
Are you talking about the Lambda expression here?

    CompanyInfo MatchedCompany = CompanyData.SingleOrDefault(c => c.ID == NewStrID);
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 500 total points
Comment Utility
The attached code snippets should make the code more maintainable.  I doubt that it will be much (if any) more efficient.

The second would be a method to update a string only if it is non-null, you would use it like this:
UpdateString(ref CData.Address1, StrAddress1);

Open in new window


You could add code so that if the string is "", then set the address to NULL.
public static void InsertOrUpdateCompanyInfo(string StrID, string StrACK,
            string StrRMID, string StrUser, string StrSec1, string StrSec2, string StrSec3, string StrSec4, string StrSec5,
            string StrCompanyType, string StrOfficeTel, string StrOfficeFax, string StrTrades, string StrCompanyReg,
            string StrCompanyName, string StrAddress1, string StrAddress2, string StrAddress3, string StrPostcode,
            string StrWebsite, string StrYearEstablished, string StrConstructionline, string StrCHAS, string StrNotes,
            string StrLocked)
{
	using (MiscDataContext dc = new MiscDataContext())
	{
		Table<CompanyInfo> CompanyData = dc.GetTable<CompanyInfo>();
		CompanyInfo CData;
		if (StrID == "")
		{
			CData = new CompanyInfo();
			CData.DateAdded = DateTime.Now;

			CompanyData.InsertOnSubmit(CData);
		}
		else
		{
			int NewStrID = Convert.ToInt16(StrID);
			CData = CompanyData.SingleOrDefault(c => c.ID == NewStrID);
			CData.DateEdited = DateTime.Now;
			CData.EditedBy = StrUser;
		}
		CData.ACK = Convert.ToInt16(StrACK);
		CData.RMID = Convert.ToInt16(StrRMID);
		CData.Sec1 = Convert.ToInt16(StrSec1);
		CData.Sec2 = Convert.ToInt16(StrSec2);
		CData.Sec3 = Convert.ToInt16(StrSec3);
		CData.Sec4 = Convert.ToInt16(StrSec4);
		CData.Sec5 = Convert.ToInt16(StrSec5);                  
		CData.CompanyType = StrCompanyType;
		CData.OfficeTel = StrOfficeTel;
		CData.OfficeFax = StrOfficeFax;
		CData.Trades = StrTrades;
		CData.CompanyReg =StrCompanyReg;
		CData.CompanyName = StrCompanyName;
		CData.Address1 = StrAddress1;
		CData.Address2 = StrAddress2;
		CData.Address3 = StrAddress3;
		CData.Postcode = StrPostcode;
		CData.Website = StrWebsite;
		CData.YearEstablished = StrYearEstablished;
		CData.Constructionline = StrConstructionline;
		CData.CHAS = StrCHAS;
		CData.Notes = StrNotes;
		CData.Locked = Convert.ToInt16(StrLocked);

		dc.SubmitChanges();
	}
}

Open in new window

///<Summary>
///  Update the 'UpdateString' only if newValue is not NULL
///</Summary>
public void UpdateIfChanged(ref string UpdateString, string newValue)
{
    if (newValue!=null)
       UpdateString=newValue;    
}

Open in new window

0
 
LVL 1

Author Comment

by:awilderbeast
Comment Utility
thanks i can see how the first bit of coding is alot better and i understand it too :)

just the second bit of code i dont get
how do i use that and where?

Thanks
0
 
LVL 21

Expert Comment

by:MogalManic
Comment Utility
Instead of doing this
           
cData.Address1 = StrAddress1;

Open in new window

you would call the updateIfChanged method:
           
UpdateIfChanged(ref cData.Address1, StrAddress1);

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Author Comment

by:awilderbeast
Comment Utility
so if i changed all the

CData.Name = StrName

to

UpdateIfChanged(ref cData.Name, StrName);

would it still work for inserting a new record in the same function?

Thanks

0
 
LVL 21

Expert Comment

by:MogalManic
Comment Utility
It will work for any entity class for insert or update.

You could put the method in a static "Utils" class so that it is something like this:
/// <summary>
/// Utility class for managing entity objects
/// </summary>
public static class EntityUtils
{
    /// <summary>
    /// Update the 'UpdateString' only if newValue is not NULL.
    /// If newValue is "", then set the UpdateString to NULL.
    /// (there will be no way to set the UpdateString to "")
    /// </summary>
    /// <param name="UpdateString">The update string.</param>
    /// <param name="newValue">The new value.</param>
    public static void UpdateIfChanged(ref string UpdateString, string newValue)
    {
        if (newValue != null)
            UpdateString = newValue;
        if (newValue.Length == 0)
            UpdateString = null;
    }
}

Open in new window

//Then the code would be :

EntityUtils.UpdateIfChanged(ref cData.Name, StrName);

Open in new window

0
 
LVL 1

Author Comment

by:awilderbeast
Comment Utility
sorry im quite new to C# and still learning

heres what im doing, tell me if im way off

the line
EntityUtils.UpdateIfChanged(ref CData.ACK, Convert.ToInt16(StrACK));

is giving out:
overloaded method string string invalid arguments, am i using it right, or can the EntityUtils only accept strings at the moment?

tried this
EntityUtils.UpdateIfChanged(ref CData.CompanyName, StrCompanyName);
gives out:
a property or index member may not be passed as an out or ref parameter

thanks for your patience

public static class EntityUtils
        {
            /// <summary>
            /// Update the 'UpdateString' only if newValue is not NULL.
            /// If newValue is "", then set the UpdateString to NULL.
            /// (there will be no way to set the UpdateString to "")
            /// </summary>
            /// <param name="UpdateString">The update string.</param>
            /// <param name="newValue">The new value.</param>
            public static void UpdateIfChanged(ref string UpdateString, string newValue)
            {
                if (newValue != null)
                    UpdateString = newValue;
                if (newValue.Length == 0)
                    UpdateString = null;
            }
        }
        public static void InsertOrUpdateCompanyInfo(string StrID, string StrACK,
                    string StrRMID, string StrUser, string StrSec1, string StrSec2, string StrSec3, string StrSec4, string StrSec5,
                    string StrCompanyType, string StrOfficeTel, string StrOfficeFax, string StrTrades, string StrCompanyReg,
                    string StrCompanyName, string StrAddress1, string StrAddress2, string StrAddress3, string StrPostcode,
                    string StrWebsite, string StrYearEstablished, string StrConstructionline, string StrCHAS, string StrNotes,
                    string StrLocked)
        {
            using (MiscDataContext dc = new MiscDataContext())
            {
                Table<CompanyInfo> CompanyData = dc.GetTable<CompanyInfo>();
                CompanyInfo CData;
                if (StrID == "")
                {
                    CData = new CompanyInfo();
                    CData.DateAdded = DateTime.Now;
                    CompanyData.InsertOnSubmit(CData);
                }
                else
                {
                    int NewStrID = Convert.ToInt16(StrID);
                    CData = CompanyData.SingleOrDefault(c => c.ID == NewStrID);
                    CData.DateEdited = DateTime.Now;
                    CData.EditedBy = StrUser;
                }
                EntityUtils.UpdateIfChanged(ref CData.ACK, Convert.ToInt16(StrACK));
                EntityUtils.UpdateIfChanged(ref CData.CompanyName, StrCompanyName);

                CData.ACK = Convert.ToInt16(StrACK);
                CData.RMID = Convert.ToInt16(StrRMID);
                CData.Sec1 = Convert.ToInt16(StrSec1);
                CData.Sec2 = Convert.ToInt16(StrSec2);
                CData.Sec3 = Convert.ToInt16(StrSec3);
                CData.Sec4 = Convert.ToInt16(StrSec4);
                CData.Sec5 = Convert.ToInt16(StrSec5);
                CData.CompanyType = StrCompanyType;
                CData.OfficeTel = StrOfficeTel;
                CData.OfficeFax = StrOfficeFax;
                CData.Trades = StrTrades;
                CData.CompanyReg = StrCompanyReg;
                CData.CompanyName = StrCompanyName;
                CData.Address1 = StrAddress1;
                CData.Address2 = StrAddress2;
                CData.Address3 = StrAddress3;
                CData.Postcode = StrPostcode;
                CData.Website = StrWebsite;
                CData.YearEstablished = StrYearEstablished;
                CData.Constructionline = StrConstructionline;
                CData.CHAS = StrCHAS;
                CData.Notes = StrNotes;
                CData.Locked = Convert.ToInt16(StrLocked);

                dc.SubmitChanges();
            }
        }

Open in new window

0
 
LVL 1

Author Comment

by:awilderbeast
Comment Utility
ok code below

and error in image
public void UpdateIfChanged(ref string UpdateString, string newValue)
        {
            if (newValue != null)
                UpdateString = newValue;
        }

        //COMPANY INFO
        public static void InsertOrUpdateCompanyInfo(string StrID, string StrACK,
            string StrRecordManager, string StrUser, string StrSec1, string StrSec2, string StrSec3, string StrSec4, string StrSec5,
            string StrCompanyType, string StrOfficeTel, string StrOfficeFax, string StrTrades, string StrCompanyReg,
            string StrCompanyName, string StrAddress1, string StrAddress2, string StrAddress3, string StrPostcode,
            string StrWebsite, string StrYearEstablished, string StrConstructionline, string StrCHAS, string StrNotes,
            string StrLocked)
        {
            using (MiscDataContext dc = new MiscDataContext())
            {
                Table<CompanyInfo> CompanyData = dc.GetTable<CompanyInfo>();
                CompanyInfo CData = new CompanyInfo();
                if (!String.IsNullOrEmpty(StrID))
                {
                    int NewStrID = Convert.ToInt16(StrID);
                    CData = CompanyData.SingleOrDefault(c => c.ID == NewStrID);
                    CData.EditedBy = StrUser;
                    CData.DateEdited = DateTime.Now;

                }
                else
                {
                    CData.RecordManager = StrUser;
                    CData.DateAdded = DateTime.Now;
                }
                UpdateIfChanged(ref CData.ACK, StrACK);

Open in new window

Untitled-1.png
0
 
LVL 1

Author Closing Comment

by:awilderbeast
Comment Utility
thanks
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now