0

I'm trying to convert my list to a string array. My list is contains the following:

public class AcctList
{
    public string sRole { get; set; }
    public bool bIsPrimary { get; set; }
    public int iDayNo { get; set; }
    public bool bIsAirportMeetGreet { get; set; }
    public bool bIsSeaportMeetGreet { get; set; }
}

I then try to convert the list to a string array by doing the following:

 List<AcctList> userAccount = AccountBLL.GetUserInfoListByName(sUser);

String[] array = userAccount.ToArray();

However I cannot convert the list to an array. What can I do so that my list can be converted to an array?

1
  • 1
    It's obvious that you can't convert a list of AcctList to array of string. The same way you can't convert a single AcctList to a single string. You have to say how that kind of conversion should be performed first. Do you want to serialize AcctList instance into XML/JSON? Do you want just one property out of that object? Something else? Compiler will not make guesses here. Neither will I. Commented Oct 1, 2014 at 0:16

2 Answers 2

2

That's because calling the ToArray() method will create an array of the type of the list, in this case, a AcctList[]. If you want to convert it to a string representation, you need to say HOW. One example could be using LINQ with the Select() method, like userAccount.Select(x => x.ToString()).ToArray() or userAccount.Select(x => x.sRole).ToArray().

Now, if you want to show information more than sRole you could use the first method and make your class override the ToString() method. Alternatively, you could format directly in the lambda expression. For example, userAccount.Select(x => String.Format("Role={0},IsPrimary={1}", x.sRole, x.bIsPrimary).

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

2 Comments

x => x.ToString() will give you an array of "Whatever.The.Namespace.Is.AcctList".
@MarcinJuraszek yes, I know, but is a valid conversion. If OP wants to add information other than the sRole, overriding ToString() and using it in the select would be the way to go. Editted the answer to provide more information on this matter (formatting).
1

Here is the modified class, you have to override your "ToString" method.

public class AcctList
{
    public string sRole { get; set; }
    public bool bIsPrimary { get; set; }
    public int iDayNo { get; set; }
    public bool bIsAirportMeetGreet { get; set; }
    public bool bIsSeaportMeetGreet { get; set; }

    public override string ToString()
    {
        return base.ToString();
        //return your desired string here
    }
}

Then using Linq select the ToString of each object.

string[] strings = userAccount.Select(p => p.ToString()).ToArray();

Hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.