7

With .NET 4.0, I sometimes have a Guid[] or 200 items that all need conversion to string[], and sometimes I have to do the reverse.

What is the fastest/smartest way to do that?

Thanks.

2
  • This is something you can and should test for yourself. Please post the code you have written so far. Commented Apr 18, 2011 at 1:33
  • myguids.Select(Guid.Parse).ToArray() Commented Apr 18, 2011 at 1:46

3 Answers 3

25

An alternative to LINQ is Array.ConvertAll() in this case:

Guid[] guidArray = new Guid[100]; ... string[] stringArray = Array.ConvertAll(guidArray, x => x.ToString()); guidArray = Array.ConvertAll(stringArray, x => Guid.Parse(x)); 

Runtime performance is probably the same as LINQ, although it is probably a tiny bit faster since it's going from and to array directly instead of an enumeration first.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for performance, because it can preallocate an array of the correct size.
That is awesome. I forgot about ConvertAll() completely. Thanks!
@dagkbyk @Snowy: If performance is a consideration, I would say you should profile them - I would guess the LINQ version is actually going to be faster, because it does not need to allocate an array (it just returns the strings as you request them). Also, it does not require using arrays, which is always a good thing.
@BlueRaja: the question was specifically about array conversion, if arrays are not needed it's a different story
3

Well, if you wanted to use LINQ, myList.Select(o => o.ToString()) will do it.

Otherwise, filling a List with a foreach loop is almost as succinct, and will work with older versions of .Net.

Comments

2

See if it helps:

Guid[] guids = new Guid[200]; var guidStrings = guids.Select(g => g.ToString()); var revertedGuids = guidStrings.Select(g => Guid.Parse(g)); 

1 Comment

I just think you are looking for a most efficient way for the conversion; I am not sure, but it's the easiest way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.