- Home /
The question is answered, right answer was accepted
Sort List by string field
So I have a class Monobehavior not serialized called "ClientObj" with a public string field called "c_name".
Then, in another Monobehaviour class I init and populate a List called "cList" storing datas I need.
I'm now trying in the same other class to sort the list by using the field "c_name" (alphabetically).
cList.Sort((c1,c2)=>c1.c_name.CompareTo(c2.c_name));
This code can't find the "c_name" field.
var newList = cList.OrderBy(c=>c.c_name).ToList();
Using Linq either won't find the "c_name" field.
What am I missing? I searched all around google but none seems to have this issue, I think it's related to the mono class I use to store the data, but I can't find any help in docs either..
I read for linq I need to use Properties, so then how do I declare only "c_name" to be as such?
Please, provide more context : How the list is declared and the class whose instances are in the list.
Answer by Vicarian · Jan 09, 2019 at 02:24 PM
Make a property that encapsulates c_name
and use that in your Linq statements.
public c_name;
public Name { get { return c_name; } }
var newList = cList.OrderBy(c=>c.Name).ToList();
This certainly isn't the solution. As stated in the question the c_name field is declared public so there is no issue accessing it in the lambda expression. If he can't find the c_name field he can't find the property as well. The question is actually lacking important details which are necessary to actually understand the problem.
You are right, too. Let me explain.
Linq OrderBy() function stores the data in a new List<> and I assumed wrong that it was going to store the field data (string in this case). Since I had instanciated that list before in the code, I did it as List of strings.
Instanciating it as Vicarian suggested with "var" works. To complete the answer, must be said that the new List has to be of the same class used for the list to compare.
In this case for example :
List<ClientObj> newList = new List<ClientObj>();
newList = cList.OrderBy(c=>c.Name).ToList();
To be fair, I almost never use anonymous declarations, preferring ins$$anonymous$$d to explicitly declare the type of the variable I want. I just copied a bit of your snippet and modified it.