• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 61
  • Last Modified:

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?
0
mastiSoft
Asked:
mastiSoft
  • 7
  • 5
  • 2
  • +1
2 Solutions
 
AndyAinscowFreelance programmer / ConsultantCommented:
>>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

0
 
MishaProgrammerCommented:
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

0
 
mastiSoftAuthor Commented:
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
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
mastiSoftAuthor Commented:
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.
0
 
MishaProgrammerCommented:
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

0
 
mastiSoftAuthor Commented:
the same error Misha. It's not working this way.
Capture.PNG
0
 
MishaProgrammerCommented:
Type of return value of your method is byte[] ! But you return List<byte>

public List<byte> ReturnArray ()
{
List<byte> list = new List<byte>(); 
return list; // type of variable "list" is equal type of method return value 

}

Open in new window


Sorry, I don`t notice this error in your first screen shot
0
 
mastiSoftAuthor Commented:
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?
0
 
MishaProgrammerCommented:
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.
0
 
mastiSoftAuthor Commented:
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.
0
 
MishaProgrammerCommented:
If your function "ReturnArray" return list now, and you want to set this value to variable ''array' with type byte[]  => it is not work.
Both types must be identical.

Also I can not see function =)  It must be:
 byte[] array = ReturnArray().ToArray()

Open in new window

0
 
it_saigeDeveloperCommented:
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:Capture.PNG-saige-
0
 
mastiSoftAuthor Commented:
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.
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
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.
0
 
mastiSoftAuthor Commented:
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
            }
           
        }
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 7
  • 5
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now