Link to home
Start Free TrialLog in
Avatar of mastiSoft
mastiSoft

asked on

return list from function

HI.
I have an function that have to return list. If I fill up list byte by byte there is no problems.
List<byte> list = new List<byte>();
   for (int i=0; i<SourceArray.Length;i++)
            {
               
                list.Add(SourceArray[i]);
            }
  return list.ToArray();

But I need to put the entire array to the list like this
List<byte> list = new List<Byte>(SourceArray);
the problem is with return now. It gives error .
Any ideas?
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

>>Any ideas?
Leave the working code alone.  (If it isn't broken don't fix it).


ps.
In your functional code you have an array.  You then add each member of the array to a list.  Then you convert the list to an array.  

Why not use this instead?
/*List<byte> list = new List<byte>();
   for (int i=0; i<SourceArray.Length;i++)
            {
               
                list.Add(SourceArray[i]);
            }
  return list.ToArray();*/
return SourceArray;

Open in new window

What is the errors?
If you have array of byte and want list of byte, can you use method ToList() ?
Try to use this code:
// Example input data
byte[] SourceArray= new byte[4];
			array[0] = 0;
			array[1] = 1;
			array[2] = 2;
			array[3] = 3;
List<byte> list = new List<byte>();
list  = SourceArray.ToList();

Open in new window

Avatar of mastiSoft
mastiSoft

ASKER

Here I attach the screen shot with code and error , I suspect that the problem is in declaration of the function: public byte[] ReturnArray() but how do I do public List ReturnArray() will not works.
Capture.PNG
I would like to leave working code alone, but I have to work with a big arrays coming with high speed. Passing data byte by byte to the list will take much more time then copy entire array to the list.
You can see this error, because there is a situation,  when variable "list" is not initialize, but you return this variable. If SourceArray,Length <= 0 -> "list" is not initialize.

If you sure, that this check is nessesary, initialize "list" at the first row.
List<byte> list = new List<byte>();
// do somethig
if(SourceArray.Length > 0)
{
    list  = SourceArray.ToList()
}
// else "list" will  be initialize , but whithout values
return list

Open in new window

the same error Misha. It's not working this way.
Capture.PNG
ASKER CERTIFIED SOLUTION
Avatar of Misha
Misha
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Tank you Misha , this part is working now. But how I convert list to the array again. That was a function but it was calling from another part of the project which need byte[] array to works. How I convert the list to the byte array or another type of array?
No problem. If you want see an array in another place of your code, you can use method ToArray();
List<byte> list = new List<byte>();
list.Add(0);
list.Add(1);
list.Add(2);
byte[] array = list.ToArray();

Open in new window

But are you sure, that it is nessesary to use list and array at the same time? Better aproach is using somethig one for the same data. It is better for system resources and more beautyfull.
this is the event that call the function
private void button1_Click(object sender, EventArgs e)
        {

            byte[] array = ReturnArray.ToArray();
        }
The function is working now thanks to you but I can't get the return from it to my event.  ReturnArray is name of the function that returns the list.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I don't know what you are after specifically but Andy is correct, you already create a source array, why convert it to a list just to return the list as an array.  Anyhow, List takes an enumerable of the identified type as a parameter so this is valid:
var myByteArrayAsAList = new List<byte>(SourceArray);

Open in new window


Proof of concept:
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29093878
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] source = ReturnArray();
            Console.WriteLine($"Contents of array: {{{string.Join(", ", source.Select(x => x.ToString()))}}}");
            List<byte> converted = ConvertArrayToList(source);
            Console.WriteLine($"Contents of converted array: {{{string.Join(", ", converted.Select(x => x.ToString()))}}}");
            Console.ReadLine();
        }

        static byte[] ReturnArray()
        {
            return new byte[] { 0xA1, 0xA2, 0xFF, 0xEF, 0x10 };
        }

        static List<byte> ConvertArrayToList(byte[] source)
        {
            return new List<byte>(source);
        }
    }
}

Open in new window

Which produces the following results:User generated image-saige-
I actually don't know the size of the byte array I will receive in function ReturnArray() . That's why I use the list, as I understand C# don't support re sizable arrays.  I'm a new in C# I used to program using another language and there it was ok to set size of array depending of the amount of data was received from device.
What I try to do :
1. send command to device (from xaml.cs file to class)
2. receive the answer from device (X amount of bytes) (class)
3. send received data back (from class to xaml.cs)
4. use the received data for processing and so on (it have to be a byte array)
I'm not so familiar with List and that's why I asking for help.
Probably a bit late but why didn't you explain that instead of asking about converting an array into a list?  (Because you now say you will never have an array as the source as you will not know the size required).

Just use a List as the data collection EVERYWHERE in your code and convert the list to an array (list.ToArray function) if you actually need an array.
thank you to all who helped me to resolve this problem. Unfortunately I can only select one Best Solution and Misha helped me all way, thank you.
Summary how we all fixed this in case another people have the same question.
Class:
  public List<byte> ReturnArray() //this is was the problem number 1
        {
            List<byte> list = new List<byte>();
            byte[] SourceArray = new byte[5];//just create a test array
            SourceArray[0] = 0xA1;
            SourceArray[1] = 0xA2;
            SourceArray[2] = 0xFF;
            SourceArray[3] = 0xEF;
            SourceArray[4] = 0x10;
            if (SourceArray.Length>0)
            {
                list = SourceArray.ToList();
            }
            else
            {
                //do something
            }

            return list;
        }

Call function from code:
  Class_List.TestClass mytest;
        public Form1()
        {
            InitializeComponent();
            mytest = new Class_List.TestClass();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            byte[] answer = mytest.ReturnArray().ToArray(); //convert the list to the byte array
            for (int i=0; i<answer.Length;i++)
            {
                listBox1.Items.Add(answer[i].ToString());//just to check if it's works
            }
           
        }