Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending and filtering C# arrays

Tags:

c#

I have been doing a lot of List<SomeType> - > SomeType[] conversion lately, especially when I'm filtering or extending arrays.

For example filtering:

// filter the list
var memberList = new List<MemberType>();
foreach (var member in members)
{
    if (member.someProperty != sentinalValue)
    {
        memberList.Add(member);
    }
}
// overwrite the old array with a new on dimensioned correctly
members = new MemberType[memberList.Count];
memberList.CopyTo(members);

or extending:

// create the new member
var newMember = new MemeberType();
// create a new array to hold the extended members
newMembers = new MemberType[members.Length + 1];
// copy over the old members
members.CopyTo(newMembers, 0);
// add the new member
newMembers[members.Length] = newMember;
// overwrite old array with new array containing new member
members = newMembers;

I have to use arrays (MemberType[]) instead of a nice generic collection because of the XML Serialization classes we use. I feel confident there is a nicer way to do this simple sort of thing so if you know of one (that doesn't add undue complexity) let me know.

like image 275
James Fassett Avatar asked Dec 12 '22 06:12

James Fassett


2 Answers

There are extension methods to do exactly what you've described:

var membersList = members.ToArray();
like image 80
jvenema Avatar answered Dec 29 '22 16:12

jvenema


members = memberList.Where(m => m.someProperty != sentinelValue).ToArray();

members = members.Concat(new[] { newMember }).ToArray();
like image 31
Domenic Avatar answered Dec 29 '22 17:12

Domenic