Bohn
Bohn

Reputation: 26919

Comparing Case Insensitive strings in a List of Objects with a Hash

I have a list of strings like this:

    List<string> excelList = new List<string>();
    excelList.Add("ZArA");  excelList.Add("CalviN"); excelList.Add("BaD ZAra");

And I create a Hashset from it like this:

var hashet = new HashSet<string>(excelList,StringComparer.OrdinalIgnoreCase);

And then I have a list of objects of a class like this:

public class MyDbObjects
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
}

List<MyDbObjects> dbObjectses = new List<MyDbObjects>();

// call .add here to add some actual objects to it.

Ok now I want to make sure that ALL the string values in the excelList are existent in my class objects list of dbObjectses as a FirstName or LastName and DON'T CARE ABOUT CASE SENSITIVITY . My code below works BUT it does NOT handle case sensitivity. How do I add that to it?

    var allofThemExist = dbObjectses.All(x => hashet.Contains(x.FirstName) || hashet.Contains(x.LastName));

Upvotes: 0

Views: 99

Answers (2)

Magnus
Magnus

Reputation: 46929

This should do it:

var hasAll = !excelList.Except(
                dbObjectses.Select(x => x.FirstName).Concat(
                dbObjectses.Select(x => x.LastName)), 
              StringComparer.OrdinalIgnoreCase).Any();

Except uses hashtables internally so should have good performance.

Upvotes: 2

Uzair Ahmed
Uzair Ahmed

Reputation: 36

instrad of hasset, use the excelList,

var allofThemExist = dbObjectses.All(x => excelList.Contains(x.FirstName) || excelList.Contains(x.LastName));

Upvotes: 1

Related Questions