I have a table in SQL server with 4 columns as shown below,
ID ColName Value Identifier
1 Name Test User 1 A100
2 Country USA A100
3 Name Test User 2 A101
4 Gender Male A101
5 Country France A101
6 Name Test User 3 A102
7 Country USA A102
8 Name Test User 1 A103
9 Country USA A103
Using C# Linq, I am trying to find out if a value already exists in the above table. For example, let's say I have a value like, Name = Test User 1 and Country = USA, how can i efficiently check if these values already exists in the above table?
I have tried an approach but, it is extremely slow with larger data in the table,
var userName = "Test User 1";
var country = "1-USA";
var results = records.SelectMany(x => x.UserDetails).Where(x => x.ColName.Equals("Name") &&
!string.IsNullOrEmpty(x.Value) && x.Value.Equals(userName )).ToList();
if (results != null && results.Count > 0)
{
var identifiers = results.Select(x => x.Identifier).Distinct().ToList();
var matchingCountries = records.SelectMany(x => x.UserDetails).
Where(x => x.ColName.Equals("Country") && identifiers.Contains(x.Identifier)).ToList();
var infoList = results.Select(x => new SearchInfoList { Name = x.Value, Identifier = x.Identifier,
Country = (matchingCountries.Where(r => r.Identifier.Equals(x.Identifier)).Select(r => r.Value).FirstOrDefault()) }).ToList();
infoList = infoList.Select(x => { x.Country = Helper.IncludeCode(codes, x.Country); return x; }).ToList();
int recordCount = infoList.Where(x => x.Name.Equals(userName) && x.Country.Equals(country)).Count();
if (recordCount > 0)
{
return true;
}
}
Is there any simple way using C# Linq to check if there is a matching name/country combination with same identifier already exists in the above table? Thanks in advance.