GPGVM
GPGVM

Reputation: 5619

Update Indexer Specified List<T> Item while building another List<T>

I have a List and want to update certain items determined by their index while stuffing them into another list.

I have this class:

public class Offer
{
  public string LineId {get; set;}
}

I populate it in code prior to the section in question.

List<Offer> offersV2...snip...

Now I want to take specific items and put them into another list but first I need to update the LineId. So I've been trying variations of this:

var offersListX2 = new List<List<Offer>>()
{
   new List<Offer>() { offersV2[0].LineId = "1"},
   new List<Offer>() { offersV2[8].LineId = "13"} 
}

Intellisense (which is just using reflection so not always accurate) says I'm good to go but at compile time I get an error saying can't convert from Offer to string. So my List appears to be projecting the object prior to updating the property.

So I tried GetElement instead of using the indexer same error at compile.

var offersListX2 = new List<List<Offer>>()
{
   new List<Offer>() { offersV2.GetElement(0).LineId = "1"},
   new List<Offer>() { offersV2.GetElement(8).LineId = "13"} 
}

If I abstract out to a helper method like this it works fine.

var offersListX2 = new List<List<Offer>>()
{
   new List<Offer>() { MyHelperMethod(offersV2[0], "1"},
   new List<Offer>() { MyHelperMethod(offersV2[8], "13"} 
}

So my question is if I can do this in Linq / Lambda etc. eliminating the helper method.

Thanks

Upvotes: 1

Views: 33

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156524

I find that it helps to make code more clear if you make a clear separation between imperative code that has side-effects and more functional code that does data transformations. Here's what I'd suggest:

offersV2[0].LineId = "1";
offersV2[8].LineId = "13";

var offersListX2 = new List<List<Offer>>()
{
   new List<Offer>() { offersV2[0] },
   new List<Offer>() { offersV2[8] } 
};

LINQ could be useful if you're trying to make a list based on many of the values in offersV2, based on some criteria.

var offersListX2 = offersV2.Where(...).Select(o => new List<Offer> {o}).ToList();

But I wouldn't recommend it when you're just including two predefined values like this. And I should mention that the fact that you're accessing indexes with constant numbers and setting values with magic strings is a huge code smell. Should offersV2 be a class rather than a list, perhaps? Or should this information be coming from some kind of collection? Think on it.

Upvotes: 2

Related Questions