EGN EGN - 2 months ago 22
ASP.NET (C#) Question

How to avoid duplicating Lambda Expression in Short If?

Is there a way to avoid writing lambda expression twice when it comes inside a short if? I constantly find myself in this situation and the only way I know is writing it again!

For the sake of giving an example, here is a case I needed to check for the length of a string!

communications.Select(c => new XElement("node",
new XAttribute("guid", Guid.NewGuid()),
new XAttribute("title", c.CommunicationDetails.Where(x => x.CultureCode == culture).FirstOrDefault().Title.Length < 40 ? c.CommunicationDetails.Where(x => x.CultureCode == culture).FirstOrDefault().Title : c.CommunicationDetails.Where(x => x.CultureCode == culture).FirstOrDefault().Title.Substring(0, 40)),
new XAttribute("isHidden", false))))

Tim Tim
Answer
Func<IEnumerable<CommunicationDetails>, string> getFirstDtlTitle = ((dtls) => dtls.Where(x => x.CultureCode == culture).FirstOrDefault()?.Title ?? "");

communications.Select(c => new XElement("node",
                               new XAttribute("guid", Guid.NewGuid()),
                               new XAttribute("title", getFirstDtlTitle(c.CommunicationDetails).Length < 40 ? getFirstDtlTitle(c.CommunicationDetails) : getFirstDtlTitle(c.CommunicationDetails).Substring(0, 40)),
                               new XAttribute("isHidden", false))))

Would be the first stab at the refactor.

Although I would also make an extension method for string to trim to max length so you would only need one call to the lambda.

So you would end up with something like this

Func<IEnumerable<CommunicationDetails>, string> getFirstDtlTitle = ((dtls) => dtls.Where(x => x.CultureCode == culture).FirstOrDefault()?.Title ?? "");

communications.Select(c => new XElement("node",
                               new XAttribute("guid", Guid.NewGuid()),
                               new XAttribute("title", getFirstDtlTitle(c.CommunicationDetails).TrimToLength(40),
                               new XAttribute("isHidden", false))))