15,559,455 members
1.00/5 (1 vote)
See more:
I have table(Records) like an
Id  Data1 Data2
1     A     B
2     C     C
3     D     D
4     B     A
5     C     D
6     A     A
7     D     D

I need the Count of matched rows like (matched = 4 & unmatched = 3) using Entity Framework

and i have done the code like below. and i got what i expected result and i need to avoid the performance as well code reducing.

C#
int totalUnAttemptsCount = 0;
string[] aa = (from a in db.ALBulkTestResults where a.CandidateID == candidateId select a.Answer).ToArray();
string[] bb = (from a in db.ALBulkTestResults where a.CandidateID == candidateId select a.CandidateAns).ToArray();

for (int i=0; i<aa.Length; i++ )
{
string comp1 = aa[i];
string comp2 = bb[i];
if(comp1 == comp2)
{
}
else
{
if (comp2 == "N")
{
ViewData["totalUnAttemptsCount"] = totalUnAttemptsCount++;
}
else
{
}
}
}
Posted
Updated 30-Nov-15 14:41pm
v3
Patrice T 30-Nov-15 15:06pm
Homework ?

## Solution 1

Yes, you can achieve the same by writing very simple LINQ query.
Code sample is given below:
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Customer cust = new Customer();

List<Customer> custList = cust.GetCustomerData();
int matchedCount = custList.Where(p => p.Data1 == p.Data2).Count();
int unmatchedCount = custList.Where(p => p.Data1 != p.Data2).Count();
}
}

public class Customer
{
public int Id { get; set; }
public string Data1 { get; set; }
public string Data2 { get; set; }

public List<Customer> GetCustomerData()
{
return new List<Customer> {
new Customer () {  Id = 1, Data1 = "A",Data2 = "B"},
new Customer () {  Id = 2, Data1 = "C",Data2 = "C"},
new Customer () {  Id = 3, Data1 = "D",Data2 = "D"},
new Customer () {  Id = 1, Data1 = "B",Data2 = "A"},
new Customer () {  Id = 1, Data1 = "C",Data2 = "D"},
new Customer () {  Id = 1, Data1 = "A",Data2 = "A"},
new Customer () {  Id = 1, Data1 = "A",Data2 = "B"},
new Customer () {  Id = 1, Data1 = "D",Data2 = "D"}
};
}
}
}

v6

## Solution 2

You are doing a lot of extra work.
The main thing is to reduce to a single pass through the data.
Also, don't update ViewData until the end of the analysis.
C#
int totalUnAttemptsCount = 0;
const string NoAttempt = "N";
foreach (var a in db.ALBulkTestResults)
{
{
}
{
++totalUnAttemptsCount;
}
else
{
}
}
ViewData["totalUnAttemptsCount"] = totalUnAttemptsCount;