How can I pass e.g 2 strings to Func and return a string?
Let say I would like to pass FirstName and LastName and the result should be like FirstName + LastName;
Moreover, I would like to have a Func declared as a property.
Please take a look at my code:
public class FuncClass
{
private string FirstName = "John";
private string LastName = "Smith";
//TODO: declare FuncModel and pass FirstName and LastName.
}
public class FuncModel
{
public Func<string, string> FunctTest { get; set; }
}
Could you please help me to solve this problem?
This should do the trick:
public class FuncModel
{
//Func syntax goes <input1, input2,...., output>
public Func<string, string, string> FunctTest { get; set; }
}
var funcModel = new FuncModel();
funcModel.FunctTest = (firstName, lastName) => firstName + lastName;
Console.WriteLine(funcModel.FuncTest("John", "Smith"));
Related
i'm very new to programming and in the progress of learning.
here is my code
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
Person p = new Person("john", "doe", tittles:null);
Person td = new Person("tom","jones");
Person w = new Person();
Console.WriteLine(td);
Console.WriteLine(p.SayHello("vahid"));
var str = p.SayHello("nick");
Console.WriteLine(str);
p.DoSome();
var m = w.Tittles[0];
Console.WriteLine(m);
}
}
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
private string[] tittles = new string[6] {
"Mr","Mrs", "Miss","Sir", "Doctor","Sister"
};
public string[] Tittles
{
get { return tittles; }
set { tittles = value; }
}
public Person()
{
}
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public Person(string firstName, string lastName, string[] tittles )
{
FirstName = firstName;
LastName = lastName;
Tittles = tittles;
}
public override string ToString()
{
return "Welcome to C# " + Tittles[0] + " " + FirstName + " " + LastName;
}
public string SayHello(string name)
{
return "hello " + name;
}
public void DoSome()
{
Console.WriteLine(FirstName + " "+ LastName + " this is a void method.");
}
}
}
my question is how to give other value than null in Person p = new Person("john", "doe", tittles:null);
tittles is my string array
i tried tittles[1] forexample but end up with an error.
is there a way this could be done?
thanks
Here's one way to do it:
Person p = new Person("john", "doe", new string[] { "one", "two" });
Or, you could use the params keyword to define a constructor that takes any number of strings:
public Person(string firstName, string lastName, params string[] tittles)
{
FirstName = firstName;
LastName = lastName;
Tittles = tittles;
}
Then you can create Person objects with any number of titles without having to create a temporary string array:
Person p = new Person("john", "doe", "one", "two");
Person j = new Person("jane", "doe", "one", "two", "three");
Person td = new Person("tom", "jones", "mr");
If you are instantiating your class with the constructor that take 3 arguments you will override the private field array titles in your class. I am assuming that you want to keep the values in there and therefore you should instantiate the class with the constructor that takes 2 arguments as that does not touch the Titles property
Person p = new Person("John", "Doe");
When instantiating with 3 args provide an array of strings like this:
Person p = new Person ("John", "Doe", new string[]{"title1", "title2"})
I created 3 objects of a class and I want to display on the console how many objects I have created (using a static class variable) - How do I do this ?
I put public static int count = 0; in the class I created but I couldn't get it to increment (count++;) based on how many objects I created of the class. I created the 3 objects in the main method and gave them values for variables.
here is the class I created in my program :
public class Student
{
public static int count = 0;
// count++;
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string birthDate;
public string BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
}
In the main method I created 3 objects of class Student:
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
// Console.WriteLine("The course contains {1} students(s) " studentCounter );
I can't get the counter to ++ based on the way I created the objects.
Increment the count in the constructor:
public class Student
{
public static int count = 0;
public Student()
{
// Thread safe since this is a static property
Interlocked.Increment(ref count);
}
// use properties!
public string FirstName { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}
You just need a constructor, there you can increment the count.
public Student()
{
count++;
}
You can increment the counter in the constructor
public Student()
{
count++;
}
To print the count variable
we should write some code like below
public static int GetCount()
{
return count;
}
and main class look like :
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
//To print the count
Console.WriteLine(" Number of Objects is : "+Student.GetCount());
}
and if we have parameterized constructor then we also have to write count++ in that constructor.
How do I go about removing the optional field from the text field that I have output using the Filehelpers library. I'm using c#
For example,
I have a shared class file
with attributes such as recordnumber, filler, payment, endingspaces
Then I need to write only recordnumber and payment into the text file without the filler.
[FixedLengthRecord(FixedMode.ExactLength)]
public partial class Person
{
[FieldFixedLength(10)]
public string FirstName;
[FieldFixedLength(10)]
public string LastName;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional1;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional2;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional3;
}
class Program
{
private static void Main(string[] args)
{
var engine = new FileHelperEngine<Person>();
Person[] allPersonRecords = GetPersonExportFromDataBase() as Person[];//This will only get the FirstName,LastName,Optional2. No result for Optional1 and Optional3
FileHelperEngine enginePerson = new FileHelperEngine(typeof(Person));
enginePerson.AppendToFile(FileName, allPersonRecords ); //Write the records to the file
//Current Output looks like this:John Lee title
//The output which I want is:John Lee title
}
}
You can use the INotifyWrite attribute to intercept the line before it is written and modify it. Here is a working example.
[DelimitedRecord(",")]
public partial class Person : INotifyWrite<Person>
{
public string FirstName;
public string LastName;
[FieldOptional]
public string Optional1;
[FieldOptional]
public string Optional2;
[FieldOptional]
public string Optional3;
public void BeforeWrite(BeforeWriteEventArgs<Person> e)
{
}
public void AfterWrite(AfterWriteEventArgs<Person> e)
{
// count the non-optional fields
var numberOfNonOptionalFields = typeof(Person).GetFields()
.Where(f => !f.GetCustomAttributes(false).Any(a => a is FieldOptionalAttribute))
.Count();
// take only the first n tokens
e.RecordLine = String.Join(",", e.RecordLine.Split(',').Take(numberOfNonOptionalFields));
}
}
class Program
{
private static void Main(string[] args)
{
var engine = new FileHelperEngine<Person>();
var export = engine.WriteString(
new Person[] {
new Person() {
FirstName = "Joe",
LastName = "Bloggs",
Optional1 = "Option 1",
Optional2 = "Option 2",
Optional3 = "Option 3"
}
});
Assert.AreEqual("Joe,Bloggs" + Environment.NewLine, export);
Console.WriteLine("Export was as expected");
Console.ReadLine();
}
}
If you want to just statically omit the optional fields (i.e. they are never used and you never want to output them) you could just create another class representing the desired output format and then convert the list from one object type to another using LINQ:
class Program
{
static void Main(string[] args)
{
// dummy test data
var originalAllPersonRecords = new Person[]
{
new Person { FirstName = "John", LastName = "Lee", Optional2 = "title" },
};//This will only get the FirstName,LastName,Optional2. No result for Optional1 and Optional3
var allPersonRecords = from p in originalAllPersonRecords select new OutputPerson{ FirstName = p.FirstName, LastName = p.LastName, Optional2 = p.Optional2 };
FileHelperEngine enginePerson = new FileHelperEngine(typeof(OutputPerson));
string fileName = "Wherever you want the file to go";
enginePerson.AppendToFile(fileName, allPersonRecords); //Write the records to the file
//Current Output looks like this:John Lee title
//The output which I want is:John Lee title
}
}
//New class added representing the output format
[FixedLengthRecord(FixedMode.ExactLength)]
class OutputPerson
{
[FieldFixedLength(10)]
public string FirstName;
[FieldFixedLength(10)]
public string LastName;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional2;
}
[FixedLengthRecord(FixedMode.ExactLength)]
class Person
{
[FieldFixedLength(10)]
public string FirstName;
[FieldFixedLength(10)]
public string LastName;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional1;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional2;
[FieldOptional]
[FieldFixedLength(5)]
public string Optional3;
}
Say I have a class like this:
class public Person
{
public string firstName;
public string lastName;
public string address;
public string city;
public string state;
public string zip;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
And let's further say I create a List of type Person like this:
List<Person> pList = new List<Person>;
pList.Add(new Person("Joe", "Smith");
Now, I want to set the address, city, state, and zip for Joe Smith, but I have already added the object to the list. So, how do I set these member variables, after the object has been added to the list?
Thank you.
You get the item back out of the list and then set it:
pList[0].address = "123 Main St.";
You can keep a reference to your object around. Try adding like this:
List<Person> pList = new List<Person>;
Person p = new Person("Joe", "Smith");
pList.Add(p);
p.address = "Test";
Alternatively you can access it directly through the list.
pList[0].address = "Test";
You can get the first item of the list like so:
Person p = pList[0]; or Person p = pList.First();
Then you can modify it as you wish:
p.firstName = "Jesse";
Also, I would recommend using automatic properties:
class public Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
You'll get the same result, but the day that you'll want to verify the input or change the way that you set items, it will be much simpler:
class public Person
{
private const int ZIP_CODE_LENGTH = 6;
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
private string zip_ = null;
public string zip
{
get { return zip_; }
set
{
if (value.Length != ZIP_CODE_LENGTH ) throw new Exception("Invalid zip code.");
zip_ = value;
}
}
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
Quite possibly not the best decision to just crash when you set a property here, but you get the general idea of being able to quickly change how an object is set, without having to call a SetZipCode(...); function everywhere. Here is all the magic of encapsulation an OOP.
You can access the item through it's index. If you want to find the last item added then you can use the length - 1 of your list:
List<Person> pList = new List<Person>;
// add a bunch of other items....
// ....
pList.Add(new Person("Joe", "Smith");
pList[pList.Length - 1].address = "....";
Should you have lost track of the element you're looking for in your list, you can always use LINQ to find the element again:
pList.First(person=>person.firstName == "John").lastName = "Doe";
Or if you need to relocate all "Doe"s at once, you can do:
foreach (Person person in pList.Where(p=>p.lastName == "Doe"))
{
person.address = "Niflheim";
}
I want to take a list of employees with 3 parts, employee id, last name and first name and add them to a drop down list showing last name, first name.
What I have so far is that I created a class for the employees:
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
and created a list to populate:
private List<Employee> employeeList = new List<Employee>();
this list is populated from a sql query and then sorted by last name.
foreach (DataRow row in ds.Tables["EMPLOYEE_TABLE"].Rows)
{
employeeList.Add(new Employee(int.Parse(row["EMP_ID"].ToString()),
row["LAST_NAME"].ToString(), row["FIRST_NAME"].ToString()));
}
employeeList.Sort(delegate(Employee E1, Employee E2) { return E1.lastName.CompareTo(E2.lastName); });
and everything up to that point worked exactly as I wanted it to but I cannot figure out how I populate a dropdownlist with the last name and first name values contained in the list.
code has been edited for readability
See code below:
DropDownList ddl = new DropDownList();
ddl.DataSource = employeeList;
ddl.DataTextField = "fullName";
ddl.DataValueField = "emp_Id";
I would also modify your class to include a full name field:
public class Employee
{
public int emp_Id { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
public string fullName
{
get
{
return String.Format("{0} {1}", this.firstName, this.LastName);
}
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
You could add an extra property to your class that will hold the 3 values, and use this as your DataTextField when binding the DropDownList:
Class Code
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string Text
{
get { return this.ToString(); }
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
public override string ToString()
{
return lastName + " " + firstName + " " + emp_Id;
}
}
HTML:
List<Employee> employees = new List<Employee>();
ddl.DataSource = employees;
ddl.DataValueField = "emp_Id";
ddl.DataTextField = "Text";
ddl.DataBind();
Good luck!
Example with existing properties:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "firstName";
bla.DataValueField = "emp_Id"
bla.DataBind();
I recommend this:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "fullName";
bla.DataValueField = "emp_Id"
bla.DataBind();
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string fullName get{ return firstName + " " + lastName;}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
Why don't you create a property called FullName to gets "FirstName + ' ' + LastName"? That would give you one field to deal with instead of two.
If you don't want or can't modify Employee, you may also try something along those lines:
var data = employee.Select (x =>
new KeyValuePair<int, string>(
x.emp_Id,
string.Format("{0}, {1}", x.lastName, x.firstName)
));
ddl.DataSource = data.ToList();
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();
This may also be useful if you have different pages with different dropdowns for employees, sometimes with Lastname first, sometimes with Firstname first, and maybe with and without a colon in between ...