开发者

Most efficient way to compare lots variables? C#

开发者 https://www.devze.com 2023-02-09 12:36 出处:网络
I am getting a datatable with customer data from a MySql databaes and a customer object from a web service.

I am getting a datatable with customer data from a MySql databaes and a customer object from a web service.

I want to compare every value in the datatable with the values in the object and if there is one field that differs I want to perfrom some tasks.

I know I can get the values from the datatable with:

string mCompanyName = row["Company Name"].ToString();
string mCreatedDate = row["Created Date"].Tostring();
//etc..

Then I get the values from the web service

string wsCompanyName = customer.companyName;
string wsCreatedDate = customer.createdDate;

There are about 50 fields and doing

if( mCompanyName != wsCompanyName & mCreatedDate != wsCreatedDate and so on..) (or similar)
{
    //Do something
}

seems to be a bit tedious and not very nice so how should I perform this? Is there a much better way to chuck it into a l开发者_Python百科ist and use some fancy LINQ?

Thanks in advance.


For cases like this I sometimes put them ("the objects") in something IEnumerable (make sure to "line them up") and use the SequenceEqual extension method. It performs standard Equals()'ity and is "cheap enough for my usage".

For instance:

var equal = (new object[] { row["A"], row["B"] })
    .SequenceEqual(new object[] { x.A, x.B });

This requires LINQ, of course.


I'd put them in a Dictionary and search that way:

Dictionary<string, string> mData = new Dictionary<string, string>();

mData.Add("Company Name", row["Company Name"].ToString());


Dictionary<string, string> wsData = new Dictionary<string, string>();

wsData.Add("Company Name", customer.CompanyName);

Then loop through:

foreach (KeyValuePair<string, string> pair in mData)
{
    if (wsData[pair.Key] == pair.Value) 
    { 
        // Do something
    }
}

This way, for every entry in mData (the data from your database), it will look for an entry in wsData with the same name.

I wouldn't create individual variables for each piece of data. It would be difficult to maintain, and would not scale well (lots of copy and pastes).


I think this might help you, but it needs to modify this to use in your scenerio stackoverflow link

0

精彩评论

暂无评论...
验证码 换一张
取 消