-2

I have two list

class obj1
{
  public string country{ get; set; }
  public string region{ get; set; }
}

class obj2
{
   public string country{ get; set; }
   public string region { get; set; }
   public string XYZ    { get; set; }
   public bool ToBeChanged{ get; set; }
}
  1. first list looks like:

    List<obj1> alist = new List<obj1>();
    alist.Add("US", "NC");
    alist.Add("US", "SC");
    alist.Add("US", "NY");
    
  2. second list (List<obj2> alist2) may make 1000 of entries with many combination of country and region.

I need to update the property "ToBeChanged" to "True" if second (alist2) list properties (country and region) matches to first(alist1) and false in otherwise.

Please help.

Thanks, Vaibhav

8
  • 1
    define, as precisely and detailled as possible, what exactly you mean by "matches to first". Jun 10, 2021 at 19:54
  • @FranzGleichmann : I just updated the question Jun 10, 2021 at 19:55
  • 2
    your edit did not add any relevant information at all. Jun 10, 2021 at 19:58
  • 2
    If there's a strong relationship between your obj1 and obj2 classes (especially, if obj2 is a specialization of obj1) you may want to look at inheritance. Those two class names aren't great names for classes, by the way
    – Flydog57
    Jun 10, 2021 at 19:58
  • Are you saying that if Country & Region in list 1 are not in list 2, then ToBeChanged should be false? Jun 10, 2021 at 20:00

2 Answers 2

0

Two points from the comments, and my thoughts:

  • Some aren't sure exactly what your matching criteria is. But to me it seems fairly clear that you're matching on 'country' and 'region'. Nevertheless, in the future, state this explicitly.
  • You got one comment criticizing your choice of variable names. That criticism is fully justified. Code is far easier to maintain when you have little hints as to what it's doing, and variable names are crucial for that.

Now, regarding my particular solution:

In the code below, I've renamed some of your objects to make them clear in their purpose. I'd like to rename 'obj2', but I'll leave that to you because I'm not exactly sure what you're intending to do with it, and I definitely don't know what 'XYZ' is for. Here are the renamed classes, with some added constructors to aid in list construction.

class RegionInfo {
    public RegionInfo(string country, string region) { 
        this.country = country; 
        this.region = region; 
    }
    public string country{ get; set; }
    public string region{ get; set; }
}

class obj2 {
    public obj2 (string country, string region, string XYZ) {
        this.country = country;
        this.region = region;
        this.XYZ = XYZ;
    }
    public string country{ get; set; }
    public string region { get; set; }
    public string XYZ    { get; set; }
    public bool ToBeChanged{ get; set; }
}

I'm using a LINQ Join to match the two lists, outputting only the 'obj2' side of the join, and then looping the result to toggle the 'ToBeChanged' value.

var regionInfos = new List<RegionInfo>() {
    new RegionInfo("US", "NC"),
    new RegionInfo("US", "SC"),
    new RegionInfo("US", "NY")
};
    
var obj2s = new List<obj2> {
    new obj2("US", "NC", "What am I for?"),
    new obj2("US", "SC", "Like, am I supposed to be the new value?"),
    new obj2("CA", "OT", "XYZ doesn't have a stated purpose")
};
        
var obj2sToChange = obj2s
    .Join(
        regionInfos, 
        o2 => new { o2.country, o2.region }, 
        reg => new { reg.country, reg.region },
        (o2,reg) => o2
    );
    
foreach (var obj2 in obj2sToChange)
    obj2.ToBeChanged = true;
    
obj2s.Dump(); // using Linqpad, but you do what works to display
    

This results in:

country region XYZ ToBeChanged
US NC What am I for? True
US SC Like, am I supposed to be the new value? True
CA OT XYZ doesn't have a stated purpose False
0

First of all, with LINQ you can never change the source. You can only extract data from the source. After that you can use the extracted data to update the source.

I need to update the property "ToBeChanged" to "True" if second (alist2) list properties (country and region) matches to first(alist1) and false in otherwise.

This is not a proper requirement. alist1 is a sequence of obj1 objects. I think, that you want the property ToBeChanged of a certain obj2 to be true if any of the obj1 items in alist1 has a [country, region] combination that matches the [country, region] combination of the obj2 concerned.

requirement Get all obj2 in alist2, that have a [country, region] combination that matches any of the [country, region] combinations of the obj1 objects in alist1.

You probably thought about using Where for this. Something like "Where [country, region] combination in the other list". Whenever you need to find out if an item is in another list, consider to use one of the overloads of Enumerable.Contains

The problem is, that the [Country, Region] combination in every obj2 can be converted to an object of class obj1, but if you want to check if they are equal, you will have a compare by reference, while you want a compare by value.

There are two solutions for this:

  • create an EqualityComparer that compares obj1 by Value
  • create [Country, Region] as anonymous type. Anonymous types always compare by value.

The latter is the most easy, so we'll do that one first.

Use anonymous types for comparison

First convert alist into anonymous type containing [Country, Region] combinations:

var eligibleCountryRegionCombinations = alist.Select(obj1 => new
{
    Country = obj1.Country,
    Region = obj1.Region,
});

Note that I don't use ToList at the end: the enumerable is created, but the sequence has not been enumerated yet. In LINQ terms this is called lazy or deferred execution.

IEnumerable<obj2> obj2sThatNeedToBeChanged = alist2.Select(obj2 => new
{
    CountryRegionCombination = new
    {
        Country = obj2.Country,
        Region = obj2.Region,
    },

    Original = obj2,
})
.Where(item => eligibleCountryRegionCombinations.Contains(
               item.CountryRegionCombination))
.Select(item => item.Original);

CountryRegionCombination is an anonymous type of the same type as the anonymous items in eligibleCountryRegionCombinations. Therefore you can use Contains. Because the items are anonymous type, the equality comparison is comparison by value.

The final select will remove the anonymous type, and keep only the Original.

Note that the query is still not enumerated.

foreach (var obj2 in  obj2sThatNeedToBeChanged.ToList())
{
    obj2.ToBeChanged = true;
}

It can be dangerous to change the source that you are enumerating. In this case it is not a problem, because the field that you change is not used to create the enumeration. Still I think it is safer, because of possible future changes, to do a ToList before you start changing the source.

Create an equality comparer

One of the overload of Enumerable.Contains has a parameter comparer. This expects an IEqualityComparer<obj1>

class Obj1Comparer : EqualityComparer<obj1>
{
    public static IEqualityComparer<obj1> ByValue {get;} = new Obj1Comparer();

    private static IEqualityComparer<string> CountryComparer => StringComparer.OrdinalIgnoreCase;
    private static IEqualityComparer<string> RegionComparer => StringComparer.OrdinalIgnoreCase;

    public override bool Equals (obj1 x, obj1 y)
    {
        if (x == null) return y == null;   // true if both null, false if x null, but y not null
        if (y == null) return false;       // because x not null

        // optimization:
        if (Object.ReferenceEquals(x, y)) return true;
        if (x.GetType() != y.GetType()) return false;

        return CountryComparer.Equals(x.Country, y.Country)
            && RegionComparer.Equals(x.Region, y.Region);
}

To make it easy to change equality of countries, I created a separate comparer for countries and for regions. So if later you want to compare case sensitive, or if you change Country from string to a foreign key to a table of countries, then changes will be minimal.

You also need to override GetHashCode. If x equals y, then GetHashCode should rerturn the same value. Not the other way round: if x and y different they may return the same hash code. However, code will be more efficient if you have more different Hash codes.

public override int GetHashCode (obj1 x)
{
    if (x == null) return 87966354;  // just a number

    return CountryComparer.GetHashCode(x.Country)
        ^ RegionComparer.GetHashCode(x.Region);
}

Which HashCode you return depends on how often this will be called, for instance in dictionaries, comparers like Contains, etc.

How "different" are the Countries and Regions? A different Country will probably also mean a different region. So maybe it is efficient enough if you only calculate the Hash code for the Country. If a Country has many, many regions, then it will probably be better to calculate the hash code for regions as well If a Region is only in one Country (OberAmmerGau is probably only in Germany), or in only a few Regions (how many regions "New Amsterdam" will there be?), then you won't have to check the Country at all.

Because we have an equality comparer, we don't need to convert alist to an anonymous type, we can specify that Contains should compare by value.

IEqualityComparer<obj1> comparer = Obj1Comparer.ByValue;

IEnumerable<obj2> obj2sThatNeedToBeChanged = alist2.Select(obj2 => new
{
    Obj1 = new Obj1
    {
        Country = obj2.Country,
        Region = obj2.Region,
    },

    Original = obj2,
})
.Where(item => alist.Contains(item.CountryRegionCombination, comparer))
.Select(item => item.Original);

Fast method: Extension method

The fastest method, and maybe also the most simple one, is to create an extension method.

private static IEqualityComparer<string> CountryComparer => StringComparer.OrdinalIgnoreCase;
private static IEqualityComparer<string> RegionComparer => StringComparer.OrdinalIgnoreCase;

public static IEnumerable<Obj2> WhereSameLocation(
    this IEnumerable<Obj2> source,
    IEnumerable<Obj1> obj1Items)
{
    // TODO: what to do if source == null?

    foreach (Obj2 obj2 in source)
    {
        // check if there is any obj1 with same [Country, Region]
        if (obj1Items
        .Where(obj1 => CountryComparer.Equals(obj2.Country, obj1.Country) 
                    && RegionComparer.Equals(obj2.Region, obj1.Region))
        .Any())
        {
            yield return obj2;
        }
    }
}

Usage:

IEnumerable<Obj1> alist = ...
IEnumerable<Obj2> alist2 = ...
       
IEnumerable<obj2> obj2sThatNeedToBeChanged = alist2.WhereSameLocation(alist);
3
  • I would recommend using ToHashSet on eligibleCountryRegionCombinations and then that would be the fastest.
    – NetMage
    Jun 11, 2021 at 21:12
  • Enumerable.ToHashSet is a function in .NET 5.0 and above. This requires visual studio 2019. Not sure if every company has already upgraded Jun 14, 2021 at 8:05
  • 1
    Then you can use new HashSet(<IEnumerable Expression>); instead.
    – NetMage
    Jun 15, 2021 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.