Alan2
Alan2

Reputation: 24562

How can I add have a property of a list populated with a unique number when I populate the list?

I have this code:

List<Phrase> cardSetPhrases = App.DB.GetPhrasesForCardSet(cardSetId);

The Phrase object has an int Index property.

Is there some way using LINQ that I could populate this with a sequence number for each row returned from the right hand side?

I did think about something like this:

foreach (var x in App.cardSetWithWordCount.Select((r, i) => new { Row = r, Index = i }))

But I wondering if there is a more concise way I could do it.

Upvotes: 2

Views: 39

Answers (1)

meJustAndrew
meJustAndrew

Reputation: 6613

Why don't you use the hash code for each element?

cardSetPhrases.ForEach(x => x.Index = x.GetHashCode());

For a sequence, I think you need to rely on a separate variable

int i = 0;
cardSetPhrases.ForEach(x => x.Index = i++);

Upvotes: 2

Related Questions