Reputation: 27
I'm new to defining classes. I want to define a class dubbed 'dataplane' (as it's a 2-dimensional set of data used to store csv files, and therefore might be represented as a plane in space) that inherits all methods of the class List<List<string>>
(if that is a class).
So far I've managed to declare the class and create a method to return a 'column' of data, but I can't invoke that method. I earlier had trouble with getting the class to inherit methods from the List<List<string>>
class, but got there after some research.
For some reason when I try to translate tutorials to build a method returning the column of data in a List<string>
, it doesn't let me invoke the method.
Could someone give me a clear example and Layman's terms explanation of how to declare a class that inherits from another, and write a method for it that uses the class's value?
Alternatively, could someone describe how I could use extended methods for this?
Also, in case someone has insight, here's what I have so far:
public class dataplanematrix : List<List<string>>
{
List<List<string>> dataplane;
private List<string> getColumn (int value)
{
List<string> columnValue = new List<string>();
foreach (List<string> line in dataplane)
{
columnValue.Add(line[value].ToString());
}
return columnValue;
}
}
The above code's issue is that I can't call the getColumn method.
Thanks in advance for your help.
Upvotes: 1
Views: 58
Reputation: 117047
The superficial problem is that you have declared your method private
when it should be public
.
However, your class definition is wrong. There's no need to have a field.
Just do this:
public class DataPlaneMatrix : List<List<string>>
{
public List<string> GetColumn(int value)
{
List<string> columnValue = new List<string>();
foreach (List<string> line in this)
{
columnValue.Add(line[value]);
}
return columnValue;
}
}
There's also no need to do line[value].ToString()
as line[value]
will do just fine.
You could also define your class like so:
public class DataPlaneMatrix : List<List<string>>
{
public List<string> GetColumn(int value)
{
return this.Select(line => line[value]).ToList();
}
}
Or, if you're using C# 6.0, like this:
public class DataPlaneMatrix : List<List<string>>
{
public List<string> GetColumn(int value) => this.Select(line => line[value]).ToList();
}
Upvotes: 3