0

I have a forloop that loops through an array and converts the array into a list of float.

    private List<Single> xfloats;

for (int i = 0; i < DataServerManager.instance.x.Count; i++)
{
xfloats = DataServerManager.instance.x.Select(str => (ok: Single.TryParse(str, out Single f), f)).Where(t => t.ok).Select(t => t.f).ToList();
}

I have another list of floats called 'tempList' and I want to add the results from 'xfloats' into the tempList. But I am getting the error: error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.List' to 'float'

      List<float> tempList = new List<float>();
        tempList.Add(xfloats);

How do I add a list of floats into a list of floats?

  • 4
    Maybe you're looking for `List.AddRange`. – Alejandro Aug 13 '21 at 13:11
  • or maybe simply `tempList = new List(xfloats);` or also `tempList = xfloats.ToList();` (using `System.Linq`) if it is supposed to only initialize the list once with the given array items ? – derHugo Aug 13 '21 at 13:29
  • anyway this should answer your question [AddRange to a Collection](https://stackoverflow.com/questions/1474863/addrange-to-a-collection) and [Add multiple items to a list](https://stackoverflow.com/questions/21345005/add-multiple-items-to-a-list/41508608) – derHugo Aug 13 '21 at 13:30

2 Answers2

1

It sounds in the question text like tempList will already have some data in it, but in the code samples like it looks like a new empty list. Those two situations call for different answers.

If tempList already has data:

var xfloats = DataServerManager.instance.x.Select(str => (ok: Single.TryParse(str, out Single f), f)).Where(t => t.ok).Select(t => t.f);
tempList.AddRange(xfloats);

If it does not already have data:

var xfloats = DataServerManager.instance.x.Select(str => (ok: Single.TryParse(str, out Single f), f)).Where(t => t.ok).Select(t => t.f);
var tempList = xfloats.ToList();

In both cases, xfloats will be an IEnumerable<int> rather than a List. This will help performance and memory use.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

If its a new list then

List<float> tempList = new List<float>(xfloats);

Or, if you list already exists

tempList.AddRange(xfloats);
Jay
  • 2,553
  • 3
  • 17
  • 37