HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Copy two properties from one array item to matching index in another array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itempropertiesarraytwooneanotherindexfrommatchingcopy

Problem

I have two IEnumerable objects called items and newItems. I need to update the Did and KeyDid property of each element in items with the matching Did and KeyDid from newItems. I can't just call items = newItems; since other things have a reference to items. Here's my code:

T[] arrItems = items as T[] ?? items.ToArray();
if (arrItems.Length != newItems.Count())
    throw new Exception("Item counts do not match.");

//Copy Did and KeyDid from old items to newItems
int i = 0;
foreach (T newItem in newItems)
{
    T oldItem = arrItems[i++];
    oldItem.Did = newItem.Did;
    oldItem.KeyDid = newItem.KeyDid;
}


I'm interested in a more concise way to do this, perhaps using a single LINQ expression. Any ideas how to improve this code in terms of readability, clearness, conciseness, or overall coolness?

Solution

if (arrItems.Length != newItems.Count())
        // --> BAD throw new Exception("Item counts do not match.");
        // Do not throw the Exception base here look for the real exception for example ArgumentException(if the arr come from arguments) or your custom exception:
        throw new ArgumentException();

      //Copy Did and KeyDid from old items to newItems
      for (var index = 0; index < newItems.Length; index++)
      {
        arrItems[index].Did = newItems[index].Did;
        arrItems[index].KeyDid = newItems[index].KeyDid;
      }


I do not think LINQ will give you a better solution than what you have above; you can use group by or select to create a new element in the linq query and than put it back to object! "For" in this case is very fast and it solve the problem.

Code Snippets

if (arrItems.Length != newItems.Count())
        // --> BAD throw new Exception("Item counts do not match.");
        // Do not throw the Exception base here look for the real exception for example ArgumentException(if the arr come from arguments) or your custom exception:
        throw new ArgumentException();

      //Copy Did and KeyDid from old items to newItems
      for (var index = 0; index < newItems.Length; index++)
      {
        arrItems[index].Did = newItems[index].Did;
        arrItems[index].KeyDid = newItems[index].KeyDid;
      }

Context

StackExchange Code Review Q#49196, answer score: 2

Revisions (0)

No revisions yet.