0
class A{
    public B body { get; set; }
}

class B{
    public List<C> positions { get; set; }
}

class C{
    public string NameOfWeek { get; set; }
}

class week{
    public int ID { get; set; }
    public string NameOfWeek { get; set; }
}

class SomeX{
    public List<A> MapWeekID(List<week> weekList, List<A> AList)
        {
            foreach (var a in AList)
            {
                foreach (var position in a.body.positions)
                {
                    position.NameOfWeek = weekList
                        .Where(x => x.NameOfWeek.ToString() == position.NameOfWeek)
                        .Select(y => y.NameOfWeek)
                        .FirstOrDefault();
                }
            }

            return AList;
        }
}

Here is code. How to write lambda for above foreach statement? I am trying but couldn't get hold of best solution so can anyone?

1
  • 5
    Linq is not very good when you want to modify an existing collection (AList). I suggest keeping foreach Commented Sep 5, 2018 at 22:15

2 Answers 2

1

Well, you can use the linq function SelectMany. Here is a modified version:

foreach(var position in AList.SelectMany(k => k.body.positions)) {
    position.NameOfWeek = weekList
                        .Where(x => x.NameOfWeek.ToString() == position.NameOfWeek)
                        .Select(y => y.NameOfWeek)
                        .FirstOrDefault();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Linq and Extension Methods shouldn't really try to solve everything. However, if you really need everything in the one statement, you could use this.

AList.SelectMany(x => x.body.positions)
     .ToList()
     .ForEach(
         position => 
            position.NameOfWeek = weekList.Where(x => x.NameOfWeek == position.NameOfWeek)
                                          .Select(y => y.NameOfWeek)
                                          .FirstOrDefault());

Note : If this came across my desk for code review, I'd send it back with a note asking for a refactor.

Basically, your original foreach is easy to read and maintain. It's not trying to be too fancy, and you can easily see what's going on. These qualities are way more important then getting everything in one statement.

1 Comment

Thank you for your positive comment :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.