Hope I'm asking this correctly.
I have this class:
class ListUtilities
{
private List<string> _datalist;
public ListUtilities(List<string> datalist)
{
_datalist = datalist;
}
//Method to calculate age from a date
private int getAge(string bdaystr)
{
DateTime today = DateTime.Today;
DateTime bday = new DateTime(Convert.ToInt32(bdaystr.Substring(0, 4)), Convert.ToInt32(bdaystr.Substring(4, 2)), Convert.ToInt32(bdaystr.Substring(6, 2)));
int age = today.Year - bday.Year;
if (bday > today.AddYears(-age)) age--;
return age;
}
//Method to print the data List
public void printDataList()
{
for (int i = 0; i < _datalist.Count; i++)
{
Console.WriteLine(_datalist.ElementAt(i));
}
}
//Method to calculate and print the ages
public void printAges()
{
List<int> ages = new List<int>();
for (int i = 0; i < _datalist.Count; i++)
{
string s = _datalist.ElementAt(i);
string[] data = s.Split(',');
ages.Add(getAge(data[3]));
}
Console.WriteLine("Ages:");
for (int i = 0; i < ages.Count; i++)
{
Console.WriteLine(ages.ElementAt(i));
}
}
//Method to search by surname
public string searchBySurname(string surname)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
string sname = data[1];
if (sname == surname)
return true;
else
return false;
});
return res;
}
//Method to search by phone number
public string searchByPhoneNumber(string phone)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
string phn = data[4];
if (phn == phone)
return true;
else
return false;
});
return res;
}
//Method to search by age
public string searchByAge(int age)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
int age2 = Convert.ToInt32(getAge(data[3]));
if (age2 == age)
return true;
else
return false;
});
return res;
}
//Method to sort by surname
public int sortBySurname(string x, string y)
{
string[] data_x = x.Split(',');
string sname_x = data_x[1];
string[] data_y = y.Split(',');
string sname_y = data_y[1];
return String.Compare(sname_x, sname_y);
}
//Method to sort by phone number
public int sortByPhoneNumber(string x, string y)
{
string[] data_x = x.Split(',');
int phn_x = Convert.ToInt32(data_x[4]);
string[] data_y = y.Split(',');
int phn_y = Convert.ToInt32(data_y[4]);
return phn_x.CompareTo(phn_y);
}
//Method to sort by age
public int sortByAge(string x, string y)
{
string[] data_x = x.Split(',');
int age_x = Convert.ToInt32(data_x[3]);
string[] data_y = y.Split(',');
int age_y = Convert.ToInt32(data_y[3]);
return age_y.CompareTo(age_x);
}
}
and I want to compile it in a .DLL file. I have tried doing it by the console like this:
csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs
and putting that class in a Class Library project and building it, and I get the DLL file in both cases but the problem comes when I want to use that DLL.
I create a new Project, and I do reference the DLL file, but when I want to use it, this is the problem:
And, seems that there is nothing inside the DLL:
Best regards
class ListUtilities
By default classes are internal and can only be seen from inside the same assembly - make your class public and it should work fine:
public class ListUtilities
Your class needs to be public. By default classes are internal which means they can only be seen inside of the DDLL.
You need to make you class public
public class ListUtilities
as clases are by defualt internal.
On a side note:
You may try to use Visual Studio instead of Command Line which will make things easier for you.
Related
public class CellPhoneMessagingController : ApiController
{
[HttpGet]
[Route("api/CellPhoneMessaging/{code}")]
public string burgers(string code)
{
string userCode = code;
char[] ch = new char[userCode.Length];
for (int i = 0; i < ch.Length; i++) {
ch[i] = userCode[i];
}
return ch;
}
}
I tried this but it is not returning the ch. Note: I am new in programming.
If you want it to return the characters of the string as an array, then use String.ToCharArray():
public char[] burgers(string code)
{
return code.ToCharArray();
}
Seems kinda pointless now to put that into a function, though...
The return type has a problem. Your function should have a return type of string[].
public class CellPhoneMessagingController : ApiController
{
[HttpGet]
[Route("api/CellPhoneMessaging/{code}")]
public string[] burgers(string code)
{
string userCode = code;
char[] ch = new char[userCode.Length];
for (int i = 0; i < ch.Length; i++) {
ch[i] = userCode[i];
}
return ch;
}
I need to access all the items that I have in my database and analyse each one of them. I was thinking I could save all the values into an array and then accessing them loke this:
var ocorrenciasLista = GetOcorrencias().ToArray();
for (int i = 0; i <= ocorrenciasLista.Length; i++)
{
var latitude2 = ocorrenciasLista[i][2];
}
EDIT:
Here is my GetOcorrencias()
[HttpGet]
public IEnumerable<Ocorrencias> GetOcorrencias()
{
int duracao = 2;
DateTime dataDuracao = DateTime.Now.Subtract(new TimeSpan(0, duracao, 0, 0));
var ocorrencias = _context.Ocorrencias
.Where(e => (e.Estado == Ocorrencias.EstadoOcorrencia.emAvaliacao && e.DataOcorrencia >= dataDuracao) ||
e.Estado == Ocorrencias.EstadoOcorrencia.aceite);
return ocorrencias;
}
I get an error saying "Cannot apply indexing with [] to an expression of type Ocorrencias". Ocorrencias is my main model.
In the code above I want to access the latitude of every item that is on my database. How should I do this?
If you want your method to return an IEnumerable you have to do something like this:
Say this is your class:
public class SomeClass
{
public string Name { get; set; }
}
And change the return type of your GetOcorrencias() to the following. I have a sample method here:
static IEnumerable<SomeClass[]> GetOcorrencias()
{
var data = new SomeClass[2][];
data[0] = new SomeClass[1] { new SomeClass() { Name = "A" } };
data[1] = new SomeClass[1] { new SomeClass() { Name = "B" } };
return data;
}
Now you can access it like a jagged array in your main:
var data = GetOcorrencias().ToArray();
for (int i = 0; i < data.Length; i++)
{
var datai = data[i][0];
}
so, im making small unity game and have some classes for working with big nubmer's
here is the code for class CurrLevel
public class CurrLevel {
public CurrLevel (int levelNum, string id) {
valuesLevel = "pow" + levelNum.ToString();
if(levelNum != 0){
numberFormatSci = "10^" + levelNum.ToString();
} else {
numberFormatSci = "";
}
identificator = id;
}
public string valuesLevel;
public string numberFormatSci;
public string identificator;
public int getValue(){
return PlayerPrefs.GetInt(identificator+"-"+valuesLevel);
}
public void setValue(int value){
PlayerPrefs.SetInt(identificator+"-"+valuesLevel, value);
}
public void add(int value){
PlayerPrefs.SetInt(identificator+"-"+valuesLevel, PlayerPrefs.GetInt(identificator+"-"+valuesLevel) + value);
}
public void substract(int value){
PlayerPrefs.SetInt(identificator+"-"+valuesLevel, PlayerPrefs.GetInt(identificator+"-"+valuesLevel) - value);
}
}
here is the code for class SomeCurrency
public class SomeCurrency {
public string identificator;
public CurrLevel[] levels = new CurrLevel[10];
public SomeCurrency(string id){
identificator = id;
for(int i = 0; i < 30; i=i+3){
levels[i/3] = new CurrLevel(i, identificator);
}
}
public void add(int power, double value){
int full = (int) value;
int leftover = (int) (value*1000 - full*1000);
if(power >= 3){
levels[power/3-1].add(leftover);
}
levels[power/3].add(full);
updateValues();
}
public SomeCurrency copy(SomeCurrency CurrToCopy){
SomeCurrency copy = new SomeCurrency(CurrToCopy.identificator);
for(int i = 0; i < 30; i++){
copy.levels[i/3] = CurrToCopy.levels[i/3];
}
return copy;
}
public void addAnotherCurrency(SomeCurrency anotherCurr){
for(int i = 0; i < 30; i=i+3){
this.add(i, anotherCurr.levels[i/3].getValue());
}
updateValues();
}
public bool substractAnotherCurrency(SomeCurrency anotherCurr){
SomeCurrency buffer = copy(anotherCurr);
Debug.Log(anotherCurr.levels[1].getValue());
if(canSubstract(buffer)){
Debug.Log(anotherCurr.levels[1].getValue());
// for(int i = 27; i >= 0; i-=3){
// levels[i/3].substract(anotherCurr.levels[i/3].getValue());
// }
return true;
} else {
return false;
}
}
public bool canSubstract(SomeCurrency fromWhereSubstract){
bool possible = false;
for(int i = 0; i < 30; i+=3){
fromWhereSubstract.levels[i/3].substract(levels[i/3].getValue());
if(i != 27){
if(fromWhereSubstract.levels[i/3].getValue() < 0){
fromWhereSubstract.levels[i/3+1].substract(1);
fromWhereSubstract.levels[i/3].add(1000);
}
}
}
if(fromWhereSubstract.levels[9].getValue() < 0){
possible = true;
}
return possible;
}
public void setValue(int power, double value){
int full = (int) value;
int leftover = (int) (value*1000 - full*1000);
if(power >= 3){
string beforeid = identificator+"-"+levels[power/3-1].valuesLevel;
PlayerPrefs.SetInt(beforeid,leftover);
}
string thisid = identificator+"-"+levels[power/3].valuesLevel;
PlayerPrefs.SetInt(thisid,full);
updateValues();
}
public string getStringValue(){
int maxlvl = 0;
for(int i = 27; i >= 0; i=i-3){
if(levels[i/3].getValue() > 0){
maxlvl = i/3;
break;
}
}
string result = levels[maxlvl].getValue().ToString();
if(maxlvl > 0){
string leftover = levels[maxlvl-1].getValue().ToString();
while(leftover.Length != 3){
leftover = "0"+leftover;
}
result += "." + leftover + "*" + levels[maxlvl].numberFormatSci;
}
return result;
}
public void resetValues(){
for(int i = 0; i < 30; i+=3){
levels[i/3].setValue(0);
}
}
private void updateValues(){
for(int i = 0; i < 27; i=i+3){
levels[i/3] = new CurrLevel(i, identificator);
if(levels[i/3].getValue() >= 1000){
levels[i/3].setValue(levels[i/3].getValue()-1000);
levels[i/3+1].setValue(levels[i/3+1].getValue()+1);
}
}
}
}
So basicly, in the code i create to new variables type of SomeCurrency
public NumberFormatting.SomeCurrency playerScore = new NumberFormatting.SomeCurrency("playerScore");
public NumberFormatting.SomeCurrency playerClickValue = new NumberFormatting.SomeCurrency("playerClickValue");
playerScore.resetValues();
playerScore.add(6, 1.32);
playerClickValue.resetValues();
playerClickValue.add(3, 103.831);
And later, when player clicks the button i try to substract one from another
Debug.Log(playerClickValue.levels[1].getValue());
Debug.Log(playerScore.substractAnotherCurrency(playerClickValue));
Debugger firstly print 103 (original value of playerClickValue.levels[1].getValue() from click function), then it prints 103 again (from the function substractAnotherCurrency before if(canSubstract(buffer)), but printing the same variable after this canSubstract shows the value of 783. So, my functions somehow change original value of playerClickValue every time i call substractAnotherCurrency.
What should i change to keep the playerClickValue same, but still checking can i suubstract it from another SomeCurrency, and after checking if i can - do so.
In C#, objects are passed by reference, meaning that if you modify an object in a fonction, it will be modified everywhere. You can read more about it, it will be important when coding. It seems you tried to do something like a copy somewhere, but you don't use the copy at all.
Also, are you sure you want to edit a variable in canSubstact?
The name suggest if will just return a bool and not change anything but you actually call substact in it
fromWhereSubstract.levels[i/3+1].substract(1);
I have been trying to figure this out for an hour now and have tried parsing but hasnt worked. The code below keeps giving me the error Input string not in correct format on the two lines where i convert leagueData[2] and league data[3]. Am I missing something simple ?
public static void readLeagues(string theFile, ArrayList allLeagues)
{
StreamReader inLeagues = null;
bool anyMoreLeagues = false;
string[] leagueData = new string[frmLeagues.numLeagueItems];
string[] fixtureData = new string[frmLeagues.numFixItems];
Leagues tempLeague;
Fixtures tempFix;
int numFixInLeague, leaguePrize;
if (fileOpenForReadOK(theFile, ref inLeagues))
{
anyMoreLeagues = getNext(frmLeagues.numLeagueItems, inLeagues, leagueData);
while (anyMoreLeagues == true)
{
leaguePrize = Convert.ToInt32(leagueData[2]);
numFixInLeague = Convert.ToInt32(leagueData[3]);
tempLeague = new Leagues(leagueData[0], leagueData[1],numFixInLeague,
leaguePrize);
for (int i = 0; i < numFixInLeague; i++)
{
getNext(frmLeagues.numFixItems, inLeagues, fixtureData);
tempFix = new Fixtures(fixtureData[0], fixtureData[1], fixtureData[2]
, fixtureData[3], fixtureData[4]);
tempLeague.addFixturesToLeague(tempLeague.getLeagueFixtures(),tempFix);
}
allLeagues.Add(tempLeague);
anyMoreLeagues = getNext(frmLeagues.numLeagueItems, inLeagues, leagueData);
}
}
if (inLeagues != null) inLeagues.Close();
Below is the code for the League ClassThanks, Jack
class Leagues
{
private string LeagueName;
private string LeagueSponsor;
private int LeaguePrize;
private int LeagueNumFixtures;
ArrayList LeagueFixtures;
public Leagues(string inLeagueName, string inLeagueSponsor, int inLeaguePrize,
int inLeagueNumFixtures)
{
LeagueName = inLeagueName;
LeagueSponsor = inLeagueSponsor;
LeaguePrize = inLeaguePrize;
LeagueNumFixtures = inLeagueNumFixtures;
LeagueFixtures = new ArrayList();
}
public ArrayList addFixturesToLeague(ArrayList fixturesSoFar, Fixtures theNewFixture)
{
fixturesSoFar.Add(theNewFixture);
LeagueNumFixtures = fixturesSoFar.Count;
return fixturesSoFar;
}
public void setLeagueName(string inLeagueName)
{
LeagueName = inLeagueName;
}
public void setLeagueSponsor(string inLeagueSponsor)
{
LeagueSponsor = inLeagueSponsor;
}
public void setLeaguePrize(int inLeaguePrize)
{
LeaguePrize = inLeaguePrize;
}
public void setLeagueNumofFixture(int inLeagueNumFixtures)
{
LeagueNumFixtures = inLeagueNumFixtures;
}
public void setLeagueFixtures(ArrayList inLeagueFix)
{
LeagueFixtures = inLeagueFix;
}
public string getLeagueName()
{
return LeagueName;
}
public string getLeagueSponsor()
{
return LeagueSponsor;
}
public int getLeaguePrize()
{
return LeaguePrize;
}
public int getLeagueNumFixtures()
{
return LeagueNumFixtures;
}
public ArrayList getLeagueFixtures()
{
return LeagueFixtures;
}
}
}
I would make sure that leagueData[2] and leagueData[3] are not null, and then do a TryParse on them. You should also first check that leagueData is not null or empty. I'm assuming leagueData is an array of strings
var prize = leagueData[2];
int outNum;
int leaguePrize = Int.TryParse(prize, out outNum)? outNum : 0;
couple small edits per phoog's comment
Here is the code below.
I am trying to make it so that when I click on the nextButton button it cycles to the next 3 numbers in my textfile. I cant figure out ow, what i have here should work :[
namespace GPSProject
{
class dataPoints
{
public int Count { get { return Points.Count; } }
List<dataPoint> Points;
//string p;
public dataPoints(/*string path*/)
{
Points = new List<dataPoint>();
// p = path;
TextReader tr = new StreamReader(/*p*/"C:/Test.txt");
string input;
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
Points.Add(a);
}
tr.Close();
}
internal dataPoint getItem(int p)
{
if (p < Points.Count)
{
return Points[p];
}
else
return null;
}
}
}
Above is the class that breaks down the textfile into inidividual numbers.
namespace GPSProject
{
public partial class Form1 : Form
{
private int count;
internal dataPoints myDataPoints;
public Form1()
{
myDataPoints = new dataPoints();
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
{
count++;
if (count == (myDataPoints.Count))
{
count = 0;
}
dataPoint a = myDataPoints.getItem(count);
textBoxLatitude.Text = a.CurLatitude;
textBoxLongtitude.Text = a.CurLongtitude;
textBoxElevation.Text = a.CurElevation;
}
}
}
}
Above is the Windows form
namespace GPSProject
{
class dataPoint
{
private string latitude;
private string longtitude;
private string elevation;
public dataPoint() //Overloaded incase no value available
{
latitude = "No Latitude Specified";
longtitude = "No Longtitude Specified";
elevation = "No Elevation Specified";
}
public dataPoint(string Latitude, string Longtitude, string Elevation)
{
// TODO: Complete member initialization
this.latitude = Latitude;
this.longtitude = Longtitude;
this.elevation = Elevation;
}
public string CurLongtitude { get { return this.longtitude; } }
public string CurLatitude { get { return this.latitude; } }
public string CurElevation { get { return this.elevation; } }
}
}
And finally this is the class the holds the numbers. The numbers i am trying to get the textboxes to show are cycles of CurLongtitude/Latitue/Elevation
First thing to do would be to create a proper vessle for your data: the DataPoint Entity:
class DataPoint
{
// Option 1: Field + read only property
private string _latitude;
public string Latitude { get { return _latitude; } }
// Option 2: Property + compiler generated field
public string Longitude { get; private set; }
public string Elevation { get; private set; }
// Constructor
public DataPoint(string latitude, string longtitude, string elevation)
{
// Internally in this class we use fields
_latitude = latitude;
// Unless we use property option 2
this.Longitude = longitude;
this.Elevation = elevation;
}
}
Next we could add a static method to the DataPoint class to load the data points from disk:
public static List<DataPoint> LoadFromFile (string filename)
{
// The .NET framework has a lot of helper methods
// be sure to check them out at MSDN
// Read the contents of the file into a string array
string[] lines = File.ReadAllLines(filename);
// Create the result List
List<DataPoint> result = new List<DataPoint>();
// Parse the lines
for (string line in lines)
{
string[] bits = line.Split(',');
// We're using our own constructor here
// Do watch out for invalid files, resulting in out-of-index Exceptions
DataPoint dataPoint = new DataPoint(bits[0], bits[1], bits[2]);
result.Add(dataPoint);
}
return result;
}
Now that we have all the building blocks. Let's make the application:
public partial class Form1 : Form
{
private int _index;
private List<DataPoint> _dataPoints;
public Form1()
{
// Since this is a simple test application we'll do the call here
_dataPoints = DataPoint.LoadFromFile(#"C:\Test.txt");
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
// Cycle the data points
_index++;
if (_index == _dataPoints.Count)
{
_index = 0;
}
// Get the specific data point
DataPoint dataPoint = _dataPoints[_index];
// The empty texts are UI only, so we could check them here
if (dataPoint.Latitude == null || dataPoint.Latitude == "")
{
textBoxLatitude.Text = "No Latitude Specified";
}
else
{
textBoxLatitude.Text = dataPoint.Latitude;
}
// A shorter, inline version
textBoxLongtitude.Text = String.IsNullOrEmpty(dataPoint.Longitude) ? "No Longitude Specified" : dataPoint.Longitude;
// Or if we don't care about empty texts
textBoxElevation.Text = dataPoint.Elevation;
}
}
Of course there are lots of ways to make the code even shorter, or to use modern techniques like LINQ, but I've tried not to go too far from your existing code. I haven't tried the code, I typed it here on SO :)
Also please be careful in how you format your code. Proper casing and following standards makes your code a lot easier to read by others.
MSDN has a lot of good examples and extensive documentation on the .NET Framework classes.