Convert js function to C# [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
I wanna convert the below js to C#:
js:
"pet":{
"animal":"cat",
"food": function(val) {
return (
'X: ' + val.data.value[0]
);
},
},`
I have prepared part of the C#, but not sure how to make the js food function part, any idea?
C#:
pet u= new Pet(){
animal = "cat",
},

Here are a couple of ways:
Without a Pet class:
var pet = new
{
Animal = "cat",
Food = new Func<Val,string>((val) => $"X: {val.data.value[0]}")
};
class Val { ... } // We still need to define the input object
With the Pet class:
var pet = new Pet
{
Animal = "cat",
Food = (val) => $"X: {val.data.value[0]}"
};
class Pet {
public string? Animal { get; init; }
public Func<Val, string>? Food { get; init; } // Function that takes in object of type Val and returns a string
}
class Val
{
//...
}

There's not really a C# version of this use of Object Notation. The closest you'd be able to come is an anonymous type.
I'm not sure exactly what type you're expecting val to be, so I made a quick example with val being an int:
Func<int,string> foodFunc = (int val) => "X:" + val.ToString();
var pet = new { Animal = "cat", Food = foodFunc };
If you're using this for more than one or two instances though, I'd suggest making a full class for it.
Here's the same example as a class, without the anonymous function:
Pet pet = new Pet("cat");
string food = pet.Food(4);
internal sealed class Pet
{
public string Animal { get; }
public Pet(string animal)
{
Animal = animal;
}
public string food(int val) => "X: " + val.ToString();
}

Related

Best way to create type of lists in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
What would be the best way to create a list?
List<string> Person = new List<string>() {"James", "Harry", "Jonson"};
or this one:
List<Person> Person = new List<Person>() {new Person("James"), new Person("Harry"), new Person("Jonson")};
class Person {
public string Name;
public Person(string newName) {
this.Name = newName;
}
}
Would it be better, or clearer to create types of lists that I use, or simply in this case to create a list of type string?
In this case, what is the point of Person if it only contains a single field of type string?
If you don't want to bother with having a type Person then a List<string> is sufficient, but if your data structure must contain more than just 1 field, then you should use a strongly typed list.
At a minimum, you need a type with a constructor
public class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}
public string Name {get; }
public int Age { get; }
}
static void Main()
{
List<Person> list = new List<Person>();
list.Add(new Person(...);
list.Add(new Person(...);
}
Keep it simple and start with strings.
var list = new List<string>() {"James", "Harry", "Jonson"};
If at some point you need "Person" objects, you can easily map the list onto a new list with the specific object type.
var persons = persons.Select( x => new Person(x) ).ToList();

C# Is there a good way to store multiple objects and still be easy to access [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Maybe it is hard to understand but I want to know if there is a way to store multiple variables like a 2d Array but use commands to access it easily?
Example:
ItemID = "1";ItemName = "Apple";ItemPrice = 10; ItemLocation = "Storage";
ItemID = "2";ItemName = "Bread";ItemPrice = 20; ItemLocation = "Outside";
ItemID = "3";ItemName = "TV";ItemPrice = 30; ItemLocation = "House";
So I can access it with a command like Item.Name(1); to get the name of it and Item.ID("Apple"); to get the ID of it (names and IDs are unique). So later, I can request everything when I get the ID or the Name of the item.
Something like this:
int IID = Item.ID("Bread");
string IName = Item.Name(2);
int IPrice = Item.Price(IID);
string ILocation = Item.Location(IID);
//So .ID return the ID but requires string Name
//And everything else requires the ID
Thanks in advance
-Coffee
Sry for my bad grammar still learning :x
You could create a custom list:
using System.Collections.Generic;
using System.Linq;
...
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public string ItemLocation { get; set; }
}
public class ItemList : List<Item>
{
public Item GetByName(string name)
{
return this.FirstOrDefault(x => x.ItemName == name);
}
public Item GetById(int id)
{
return this.FirstOrDefault(x => x.ItemId== id);
}
}
Then you can use it like this:
var itemList = new ItemList();
itemList.Add(new Item { ItemId = 1, ItemName = "Some Item", ItemLocation = "Wherever" });
itemList.Add(new Item { ItemId = 2, ItemName = "Some Other Item", ItemLocation = "" });
var item = itemList.GetByName("Some Item");
Not sure if I understood your question fully, but taking a jab here
There is many ways to skin this cats and here are some thoughts:
You can write a class, struct, a Tuple to model the Item type
You can have a dictionary using the ID as the key and store the item object as the value. This will allow easy and fast lookup by ID but less to search by name OR
Store the item list in standard collection like a List and use linq query to filter and find the item OR
Write your own Collection class that perhaps derive from List and then you can write custom methods such as ID(), Name() OR
Write extension methods ID(), Name(), etc. on the collection types you use like this
public static Item ID(this IList<Item> items, string name)
{
return items.SingleOrDefault(e=>e.Name == name);
}

check not null for list in a list at specific index [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
How do I access list2 in list1 below and check IsnotNull in an Assert
List<Object> list1= new List<Object>();
List<int> list2= new List<int>();
list1.add(someValue);
list1.add(list2);
Assert.IsNotNull(list1[1]..??);
Here's how:
((List<int>)list1[1]).<something>
But please use some decent variable names. Also, a List<Object> is a huge code-smell.
#RobIII shows in his answer how you can cast the object value to a List<int>; however, the real question is, how do you know what is contained at which position in list1? You will end up in a code similar to this one:
for (int i = 0; i < list1.Count; i++) {
object item = list1[i];
switch (item)
{
case int x:
// do some thing with x
break;
case string s:
// do some thing with s
break;
case IList list:
// do some thing with list
break;
....
}
}
This is going to become tedious.
A better approach is to work in an object oriented manner. Example
public abstract class Property
{
public string Name { get; set; }
public abstract void DoSomething();
}
public abstract class Property<T> : Property
{
public T Value { get; set; }
}
public class StringProperty : Property<string>
{
public override void DoSomething() =>
Console.WriteLine($"String of length {Value?.Length}");
}
public class IntListProperty : Property<List<int>>
{
public override void DoSomething() =>
Console.WriteLine($"Int list has {Value?.Count} items");
}
Now you can write
var list1 = new List<Property>{
new StringProperty { Name = "string property", Value = "hello" },
new IntListProperty { Name = "Int list", Value = new List<int>{ 2, 3, 5, 7 } }
};
for (int i = 0; i < list1.Count; i++) {
Property prop = list1[i];
Console.Write(prop.Name); Console.Write(": ");
prop.DoSomething();
}
This is called polymorphism. This means multi-shaped. You have properties of different shape, but all of them have a Name and a DoSomething method. You can call this method on properties of different type, and delegate the different things to do to these very properties. Each one of them know what it has to do.

c# casting idea explanation

i am studying C# online , and i faced this thing a couldn't understand it ,
consider this Animal class
public class Animal
{
public int Age { set; get; }
public string Name { set; get; }
public double Weight { set; get; }
public Animal()
{ }
public Animal(int Age, string Name, double Weight)
{
this.Age = Age;
this.Name = Name;
this.Weight = Weight;
}
}
And the Dog class which inherit from Animal
class Dog : Animal
{
public string color { set; get; }
public Dog()
{
}
public Dog(int Age, string Name, double Weight, string color) : base(Age, Name, Weight)
{
this.color = color;
}
public string EmptyMethod()
{
return(" i am dog method ");
}
}
In the Main method in program class
static void Main(string[] args)
{
List<Animal> MyAnimals = new List<Animal>();
List<Dog> MyDogs = new List<Dog>();
MyAnimals.Add(new Animal());
MyAnimals.Add(new Dog());
foreach (var item in MyAnimals)
{
Console.WriteLine(item.GetType().Name);
if (item is Dog)
{
Console.WriteLine(item.GetType().Name + " i am dog between Animal");
//Here i got a compiling error and can't reach the dog empty method even after checking it's a Dog object !!! Why
var tryingToReachDogMethod = item.EmptyMethod();
}
}
Animal smallAnimal = new Animal();
MyDogs.Add(new Dog());
MyDogs.Add(smallAnimal as Dog);
foreach (var item in MyDogs)
{
//Here i Can reach the Empty Method from Dog Class !!!
//i know it will give runtime error because some objects is not
//dogs and don't have it's method to implement it
var tryingToReachDogMethod = item.EmptyMethod();
if (item is Animal)
{
Console.WriteLine("i am animal as dog");
}
}
I comment My question in the third piece of code ,(the code is one of my exercises i have written few days ago) , so why would a programmer make a list of animals then put a more developed object in it (in the example object from class dog) and why any one would to do the opposite ? why to make a list from developed object (in the example dogs) and then try to put Less developed type of objects in it ,
Can you give example from real programming solution
MyDogs is a list of dogs. You can add only Dogs to it.
The problem is in this line:
MyDogs.Add(smallAnimal as Dog);
You probably think you casted the animal to a dog. That is not true. You tried to cast it, but it failed. Since you use as, it will not throw an exception, but instead will return null. Now you have a null Dog in your list. You will get a null reference exception when you try to access members of that instance.
Cause item is still Animal since you have List<Animal> MyAnimals = new List<Animal>(); and your Animal type don't have a EmptyMethod(). Thus you need to cast it to Dog type explicitly like below in order to invoke the desired method
var tryingToReachDogMethod = ((Dog)item).EmptyMethod()
(Or) You can as well use as operator along with null propagation operator like
Dog d = item as Dog;
var tryingToReachDogMethod = d?.EmptyMethod();
Real world example of where it makes sense to put a (as you call it) "more developed" version of an object inside a list defined using a base class or interface is the "Command" pattern.
Given an interface like this:
public interface ICommand
{
void Execute();
}
You might have lots of different implementations of ICommand that you want to execute one after another. You would put them all in some sort of List
var commands = new List<ICommand>();
commands.Add(new Command1());
commands.Add(new Command2());
And execute them all. You dont need to know what sort of command it is, just that they all have an Execute method
foreach(var command in commands)
command.Execute();
This demonstrates Polymorphism

Searching for a Key in Multivalue Dictionaries in C#

I want to set up a lookup table like so:
Key Value
----- ------------------
Cat Lion, Tiger, Cheetah
Fish Dolphin, Whale
Dog . Pitbull, Doberman
An input of "Lion" would return the key "Cat"
I have set up 3 possible ways to initialize the data:
A Dictionary:
var map = new Dictionary<string,string>
{
["Dolphin"] = "Fish",
["Lion"] = "Cat",
//....
};
A HashSet:
var data = new Dictionary<string, HashSet<string>>
{
{"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
{"fish", new HashSet<string> {"Dolphin", "Whale"}},
{"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};
A tuple:
var data = new List<Tuple<string, List<string>>>
{
Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),
};
Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.
Is there something similar for the other two options?
The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.
I am suggesting a bit different approach.
public abstract class Animal
{
public string Type { get; }
public string Name { get; }
protected Animal(string type, string name)
{
Type = type;
Name = name;
}
}
public class Cat : Animal
{
public Cat(string name) : base("Cat", name)
{
}
}
public class Fish : Animal
{
public Fish(string name) : base("Fish", name)
{
}
}
public static class Program
{
public static void Main(string[] args)
{
List<Animal> list = new List<Animal>();
list.Add(new Cat("Cheetah"));
list.Add(new Fish("Dolphin"));
var cheetahType = list.FirstOrDefault(animal => animal.Name == "Cheetah")?.Type;
var doplhinType = list.FirstOrDefault(animal => animal.Name == "Dolphin")?.Type;
}
}
If you don't actually need that much, you can make Animal nonabstract and define enum instead of string Type and remove derived children.
Use the Dictionary<string, string> option.
var animalToType = new Dictionary<string,string>
{
["Dolphin"] = "Fish",
["Lion"] = "Cat",
//....
};
var lionType = animalToType["Lion"];
The other options are not going to be as simple. They will all involve loops, whether directly or hidden by Linq calls.
Personally, this architecture is a bit tricky... I mean, normally the lookup is based on keys, not on values, but I understand that sometimes you need to reverse the common logics and retrieve what you need within a data structure that is adequate in many other situations, except that one!
Anyway, if I was given the choice I would go for the HashSet approach, since it can grant a uniqueness of its values and also an immediate aggregation of the subtypes. But you can eventually run a benchmark and find out the fastest lookup solution in a few minutes.
Using the aforementioned approach (the HashSet one I mean), you can retrieve your type as follows:
String animalType = data.Where(kvp => kvp.Value.Contains("Dolphin")).Select(p => p.Key).FirstOrDefault();
// Animal type found: Fish!
if (animalType != null)
Console.WriteLine("Animal type found: " + animalType + "!");
else
Console.WriteLine("No animal type found!");

Categories