diff --git a/ClosedXML/Excel/Cells/XLCell.cs b/ClosedXML/Excel/Cells/XLCell.cs index 8d30470..f7996a5 100644 --- a/ClosedXML/Excel/Cells/XLCell.cs +++ b/ClosedXML/Excel/Cells/XLCell.cs @@ -1453,7 +1453,11 @@ public IXLRange MergedRange() { - return Worksheet.Internals.MergedRanges.FirstOrDefault(r => r.Contains(this)); + return Worksheet + .Internals + .MergedRanges + .GetIntersectedRanges(this) + .FirstOrDefault(); } public Boolean IsEmpty() @@ -1547,15 +1551,9 @@ /// The data validation rule applying to the current cell or null if there is no such rule. private IXLDataValidation GetDataValidation() { - foreach (var xlDataValidation in Worksheet.DataValidations) - { - foreach (var range in xlDataValidation.Ranges) - { - if (range.Contains(this)) - return xlDataValidation; - } - } - return null; + return Worksheet + .DataValidations + .FirstOrDefault(dv => dv.Ranges.GetIntersectedRanges(this).Any()); } public IXLDataValidation SetDataValidation() @@ -2428,13 +2426,17 @@ if (copyConditionalFormats) { - var conditionalFormats = source.Worksheet.ConditionalFormats - .Where(c => c.Ranges.Any(range => range.Contains(source))).ToList(); + var conditionalFormats = source + .Worksheet + .ConditionalFormats + .Where(c => c.Ranges.GetIntersectedRanges(source).Any()) + .ToList(); + foreach (var cf in conditionalFormats) { if (source.Worksheet == Worksheet) { - if (!cf.Ranges.Any(range => range.Contains(this))) + if (!cf.Ranges.GetIntersectedRanges(this).Any()) { cf.Ranges.Add(this); } diff --git a/ClosedXML/Excel/Ranges/IXLRanges.cs b/ClosedXML/Excel/Ranges/IXLRanges.cs index 7942719..8e2448f 100644 --- a/ClosedXML/Excel/Ranges/IXLRanges.cs +++ b/ClosedXML/Excel/Ranges/IXLRanges.cs @@ -44,6 +44,12 @@ /// IEnumerable GetIntersectedRanges(IXLAddress address); + /// + /// Filter ranges from a collection that intersect the specified cell. Is much more efficient + /// that using Linq expression .Where(). + /// + IEnumerable GetIntersectedRanges(IXLCell cell); + IXLStyle Style { get; set; } diff --git a/ClosedXML/Excel/Ranges/XLRanges.cs b/ClosedXML/Excel/Ranges/XLRanges.cs index 71fc32a..f388262 100644 --- a/ClosedXML/Excel/Ranges/XLRanges.cs +++ b/ClosedXML/Excel/Ranges/XLRanges.cs @@ -131,6 +131,11 @@ .GetIntersectedRanges(address); } + public IEnumerable GetIntersectedRanges(IXLCell cell) + { + return GetIntersectedRanges(cell.Address); + } + public IEnumerable DataValidation { get { return Ranges.Select(range => range.DataValidation).Where(dv => dv != null); } diff --git a/ClosedXML_Tests/Resource/Examples/Misc/DataValidation.xlsx b/ClosedXML_Tests/Resource/Examples/Misc/DataValidation.xlsx index 64e85ed..9b36c64 100644 --- a/ClosedXML_Tests/Resource/Examples/Misc/DataValidation.xlsx +++ b/ClosedXML_Tests/Resource/Examples/Misc/DataValidation.xlsx Binary files differ