Linq expression meaning

if (regionTerritory.Any(m => m.Region == int.Parse(region.RegionCode)))
{
    // region exists, add territory
    regionTerritory.First(m => m.Region == int.Parse(region.RegionCode)).Territories.Add(int.Parse(region.TerritoryCode), region.TerritoryName);
}

Can anybody tell me what does this means ? also what is m in above code and Any, First and Add ?

Thanks in Advance.

Jon Skeet
people
quotationmark

m is the parameter to the lambda expression. It will be called with each element in the collection (as far as necessary). This is an inefficient way of writing the code, however. It would be better to use:

int regionCode = int.Parse(region.RegionCode);
var targetRegion = regionTerritory.FirstOrDefault(m => m.Region == regionCode);
if (targetRegion != null)
{
    targetRegion.Territories.Add(regionCode, region.TerritoryName);
}

Now:

  • We only parse region.RegionCode once
  • We only need to find the matching region in regionTerritory once (and then add to it)

people

See more on this question at Stackoverflow