Reputation: 1361
below is my method which I would like to optimize. and below I have written one way. Problem is I am unable to test it now, so would like to know from community, if that is correct and if there is any other way i can optimize it using linq or anything. Thanks,
method to be optimized:
private bool IsRecording(List<string> jPropertyNames)
{
bool isRecording = true;
string[] PropFromSb = new string[9] { "Id", "DocType", "Project", "ProjectId", "Tags", "Properties", "Categories", "Trigger", "Received" };
foreach (string property in PropFromSb)
{
if (!jPropertyNames.Contains(property))
{
isRecording = false;
}
}
return isRecording;
}
the way I tried(would like to know if it will fetch same result as above) :
private bool IsRecording(List<string> jPropertyNames)
{
string[] PropFromSb = new string[9] { "Id", "DocType", "Project", "ProjectId", "Tags",
"Properties", "Categories", "Trigger", "Received" };
return !PropFromSb.Except(jPropertyNames).Any();
}
Also if someone can provide any other way to further optimize this code.
Upvotes: 1
Views: 76
Reputation: 460238
Enumerable.Except
returns all which are in first which are not in second, you can translate it to "Remove all 2nd from 1st". So yes, the logic is the same as with your old code.
Why you initialize the same array over and over again in that method? Store it in a field or property which you can initialize inline or in the constructor. It was better to use a HashSet<string>
instead since there can be no duplicates and it was more efficient as well. Then you could use this code:
private bool IsRecording(List<string> jPropertyNames)
=> PropFromSb.IsSubsetOf(jPropertyNames);
Upvotes: 4
Reputation: 374
try this:
private bool IsRecording(List<string> jPropertyNames)
{
string[] PropFromSb = new string[9] { "Id", "DocType", "Project", "ProjectId", "Tags", "Properties", "Categories", "Trigger", "Received" };
return !jPropertyNames.Exists(x => PropFromSb.Any(y => y == x));
}
Upvotes: 0