0

So I'm trying to basically do an AddRange of a List where I need to call a constructor, and what I'm doing just seems unintuitive.

This is what I'm doing:

List<Affix> FinalPrefixes = new List<Affix>(), 
            FinalSuffixes = new List<Affix>();
foreach (AffixGenerator TempGenerator in PossiblePrefixes)
    FinalPrefixes.Add(new Affix(TempGenerator));

foreach (AffixGenerator TempGenerator in PossibleSuffixes)
    FinalSuffixes.Add(new Affix(TempGenerator));

Obviously a function would make this simpler, but I was wondering if there was another way to simplify it (lambda maybe).

Wrekk
  • 49
  • 3
  • 5
    I'm voting to close this question as off-topic because this is a review which should go to review.stackexchange.com – MakePeaceGreatAgain Sep 25 '17 at 14:16
  • 2
    Oh god, I'm sorry. This is my first time posting here, and I didn't realize I had to post my question elsewhere. – Wrekk Sep 25 '17 at 14:17
  • 1
    Do you really care? Your code is pretty straight-forward and easy to understand, isn´t it? From my point of view there´s no reason to change anything. – MakePeaceGreatAgain Sep 25 '17 at 14:18
  • 4
    Can you explain why it seems unintuitive? I agree with the suggestions that using a select query expression is a nice alternative, but your code seems perfectly straightforward to me. – Eric Lippert Sep 25 '17 at 14:18
  • It is somewhat easy to understand, though I think you'd need some context to understand my reasoning for wanting a simpler way of doing it. Currently, my function is somewhat large, and I'd like to "shrink" it down a bit. :) – Wrekk Sep 25 '17 at 14:21
  • 2
    For me (opinion) `foreach` is fine, though you are not following [naming guidelines](https://stackoverflow.com/q/10020705/1997232) (local variables are camel). Linq produces for beginners one-liners with side effects, means more problems. – Sinatr Sep 25 '17 at 14:23
  • Yes, camel case. A few years back I used to code in camel case, but when I started using Unreal Engine 4 and c++, I switched to pascal case. :) – Wrekk Sep 25 '17 at 14:25
  • I just want to say, nothing to be sorry about. You know now. Welcome to StackExchange. :) – Almo Sep 25 '17 at 15:29

2 Answers2

3

You can use LINQ:

var FinalPrefixes = PossiblePrefixes.Select(p => new Affix(p)).ToList();
var FinalSuffixes = PossibleSuffixes.Select(s => new Affix(s)).ToList();
Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
2

Use LINQ's Select...

var FinalPrefixes = PossiblePrefixes.Select(x => new Affix(x)).ToList();
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380