Return IEnumerable of a property of the Key in a Map - language-ext

Suppose I have the following classes:
public class X
{
public string a;
public string b;
}
public class Y
{
public string c;
}
and I have a Map:
var myMap = Map<X, Y>();
How do I return a list of a (IEnumerable<string>) from this?
I am trying to write:
myMap.Keys.Select(_ => _.a);
But this won't work. What am I missing?

The code you've written actually works fine as long as you are using System.Linq. However, if you want to create a non-empty map, your key class (X) has to derive from Record<T> as well, like this:
using System;
using System.Linq;
using LanguageExt;
using static LanguageExt.Prelude;
public class X : Record<X>
{
public string a;
public string b;
public static X Create(string a, string b)
=> new X() { a = a, b = b };
}
public class Y
{
public string c;
public static Y Create(string c)
=> new Y() { c = c };
}
class Program
{
static void Main(string[] args)
{
var myMap =
Map(
(X.Create("a1", "b1"), Y.Create("c1")),
(X.Create("a2", "b2"), Y.Create("c2")));
foreach (var str in myMap.Keys.Select(_ => _.a))
{
Console.WriteLine(str);
}
}
}
Output is:
a1
a2

Related

Java stream filter with element in a constant tab

I have two class like this :
public class Forecast {
private List<Element> elements;
private Person person;
}
public class Element {
private String element;
}
I have a constant of String[] like this :
private static final String[] ELE = {"element1", "element2", "element3"};
I would like to retrieve all the elements of my list in forecast which contains one of the elements of my constant with Stream.
So, I started by doing this to test :
public List<Element> getElement(String person) {
return getElement(person).getList()
.stream()
.filter(r -> r.get(0).getElement.equals("element1"))
.collect(Collectors.toList());
}
Now I would like to use my constant ELE, and I don't find how to go through it and test my elements
Thanks
private static final List<String> ELE_LIST = java.util.Arrays.asList(ELE);
public List<Element> getElement(String person) {
return getElement(person).getList()
.stream()
.filter(r -> ELE_LIST.contains(r.get(0).getElement()))
.collect(Collectors.toList());
}

'Named Singleton' with Google Guice

i try to implement '#Named' injection but i do not want to predefine the #Named instances (i have an example at the end, which is actually working... but not the way i want - as i predefine the names)
its easier to provide an code example than explaining what i mean.
public class NamedSingletonExample {
private static Map<String, DoubleProperty> dMap = new HashMap<String, DoubleProperty>();
public static DoubleProperty getNamedDoubleProperty(String name) {
DoubleProperty d = dMap.get(name);
if (d == null) {
d = new SimpleDoubleProperty();
dMap.put(name, d);
}
return d;
}
#Test
public void testNamedSingleton() {
System.out.println("test()");
DoubleProperty d0 = getNamedDoubleProperty("d0");
DoubleProperty d1 = getNamedDoubleProperty("d1");
DoubleProperty d0_2 = getNamedDoubleProperty("d0");
d0.set(1);
d1.set(2);
d0_2.set(4);
System.out.println("expected: false & actual -> " + (d0.get() == d1.get()));
System.out.println("expected: true & actual -> " + (d0.get() == d0_2.get()));
System.out.println("expected: true & actual -> " + (d0 == d0_2));
}
}
and this is the way i expect it to work using guice
public class NamedSingletonConsumer {
#Inject
public NamedSingletonConsumer(//
#Named("d0") DoubleProperty d0, //
#Named("d1") DoubleProperty d1, //
#Named("d0_2") DoubleProperty d0_2//
) {
// ...
}
}
i read loads of in other questions here on StackOverflow and used google (including guice doc) but was not able to find an example for this.
now the "working" example:
public class AllInOneExample {
public AllInOneExample() {
Injector injector = Guice.createInjector(new AllInOneExample.DoublePropertyModule());
DoublePropertyConsumer consumer = injector.getInstance(DoublePropertyConsumer.class);
consumer.test();
}
public static void main(String[] args) {
new AllInOneExample();
}
static class DoublePropertyConsumer {
DoubleProperty d0;
DoubleProperty d1;
DoubleProperty d0_2;
#Inject
public DoublePropertyConsumer(//
#Named("d0") DoubleProperty d0, //
#Named("d1") DoubleProperty d1, //
#Named("d0_2") DoubleProperty d0_2//
) {
this.d0 = d0;
this.d1 = d1;
this.d0_2 = d0_2;
}
public void test() {
System.out.println("test()");
d0.set(1);
d1.set(2);
d0_2.set(4);
System.out.println("expected: false & actual -> " + (d0.get() == d1.get()));
System.out.println("expected: true & actual -> " + (d0.get() == d0_2.get()));
System.out.println("expected: true & actual -> " + (d0 == d0_2));
}
}
static class DoublePropertyFactory {
private Map<String, DoubleProperty> dMap = new HashMap<String, DoubleProperty>();
public DoubleProperty buildProperty(String name) {
DoubleProperty d = dMap.get(name);
if (d == null) {
d = new SimpleDoubleProperty();
dMap.put(name, d);
}
return d;
}
}
static class DoublePropertyModule extends AbstractModule {
#Override
protected void configure() {
DoublePropertyFactory doublePropertyFactory = new DoublePropertyFactory();
requestInjection(doublePropertyFactory);
// bind(DoubleProperty.class).annotatedWith(Named.class).toInstance(doublePropertyFactory .buildProperty(???)));
bind(DoubleProperty.class).annotatedWith(Names.named("d0"))
.toInstance(doublePropertyFactory.buildProperty("d0"));
bind(DoubleProperty.class).annotatedWith(Names.named("d1"))
.toInstance(doublePropertyFactory.buildProperty("d1"));
bind(DoubleProperty.class).annotatedWith(Names.named("d0_2"))
.toInstance(doublePropertyFactory.buildProperty("d0"));
}
}
}

mvc5 N tier architecture

I am developing an mvc app with the following N tier structure:
DataAccess
Repository
Models
BusinessLogic
In my BusinessLogic folder I have an interface IClinicBusiness and a class ClinicBusiness that interfaces with IClinicBusiness.
The ClinicBusiness class is as follows:
public void AddClinic(Clinic c)
{
var cr = new ClinicRepository();
var clinc = new Clinic();
if (c != null)
{
clinc.ClinicName = c.ClinicName;
clinc.ClinicLocation = c.ClinicLocation;
}
cr.InsertClinic(c);
cr.Save();
}
}
The ClinicBusiness class implements a method from the Repository class library eg. InsertClinic();
public ClinicRepository()
{ }
public ClinicRepository(DataContext clinics)
{
this.clinic = clinics;
}
public IEnumerable<Clinic> GetClinics()
{
return clinic.Clinics.ToList();
}
public Clinic GetClinicByID(int ClinicId)
{
return clinic.Clinics.Find(ClinicId);
}
public void InsertClinic(Clinic c)
{
clinic.Clinics.Add(c);
}
In my controller I have an action
public ActionResult CreateClinic(Clinic c)
{
var clinicBusiness = new ClinicRepository();
return View(clinicBusiness.InsertClinic(c));
}
I get the following error cannot convert from 'void' to 'object'
Can someone please guide me?
Depending on your requirements, I think you want to change your repository InsertClinic method to
public Clinic InsertClinic(Clinic c)
{
clinic.Clinics.Add(c);
return c;
}
Or change your Action to
public ActionResult CreateClinic(Clinic c)
{
var clinicBusiness = new ClinicRepository();
clinicBusiness.InsertClinic(c)
return View(c);
}
Again, it just depends on what your trying to accomplish and your view model.

Creating a list from ENUM into Model

I got the following model piece of code:
public enum EnumTest
{
[Description ("Enum Text 1")]
Value_1 = 1,
[Description ("Enum Text 2")]
Value_2 = 2,
}
public List<Fields> listFields = new List<Fields>();
public class Fields
{
public int Code { get; set;}
public string Description { get; set;}
}
I got an Enum and I would like to fill my variable CODE with enum value and the variable Description with the same enum description. I looked up a long time and failed to initialize my "ListFields" into its constructor with the enum VALUE/DESCRIPTION.
I already got the enum and the method to get its description.. I found it usefull, so I'll leave it here, maybe it can be useful for someone..
public static string GetDescription(this Enum value)
{
return (from m in value.GetType().GetMember(value.ToString())
let attr =(DescriptionAttribute)m.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault()
select attr == null ? value.ToString() : attr.Description).FirstOrDefault();
}
To use this you just need to do something like this:
String xx = Enum.EnumName.GetDescription();
You have to use reflection.
public static Fields[] GetEnumFields(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
if (!enumType.IsEnum)
throw new ArgumentException("Not an enum");
FieldInfo[] fieldInfos = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
Fields[] result = new Fields[fieldInfos.Length];
for (int i = 0; i < fieldInfos.Length; ++i)
{
FieldInfo field = fieldInfos[i];
int value = (int)field.GetValue(null);
DescriptionAttribute attrib = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
string desc = attrib != null ? attrib.Description : field.Name;
result[i] = new Fields(value, desc);
}
return result;
}
public class Fields
{
private int value;
private string description;
public int Value
{
get { return this.value; }
}
public string Description
{
get { return this.description; }
}
public Fields(int value, string description)
{
this.value = value;
this.description = description;
}
}
To use it is quite simple:
enum test
{
[Description("hello!")]
ciao,
www
}
static void Main(string[] args)
{
foreach (Fields f in GetEnumFields(typeof(test)))
{
Console.WriteLine(f.Description);
}
}
In my implementation when a descriptionattribute is not found, field name is used.
We must also say that reflection can be slow and rebuilding the entire array when you need it is a waste of time, if you need it often.
You can store the array somewhere so you can compute it only once and keep it cached.
This of course and as I said, makes sense only if you need this readonly list very often.

How can refer base class instance?

The following example, how do I refer base class instance?
public class A
{
public string test;
public A()
{
B b = new B();
test = "I am A class of test.";
}
public void hello()
{
MessageBox.Show("I am A class of hello.");
}
class B
{
public B()
{
//Here...
//How can I get A class of test and call A class of hello method
//base.test or base.hello() are not working.
}
}
}
You'd have to pass a reference of A to B.
One way you can do this is as follows:
public class A
{
string name = "Class A";
public A()
{
var b = new B(this);
}
class B
{
public B(A a)
{
a.name.Dump(); // Write out the property of a.name to some stream.
}
}
}
To clearly distinguish between base class and nested class, please refer the example below.
namespace Example
{
class A
{
string Name = "test"; // access restricted only to this class
public string Type; // global access
internal string Access; // within defining namespace
protected string Code; // this class and subclass
// When you create a nested class like C, you can create instances of C within this class(A).
C c = new C();
class C
{
string name;
public C()
{
//this is a nested class and you cannot call A as its base
name = "test success";
}
}
}
class B : A
{
public string Type { get { return base.Type; } set { base.Type = value; } } // You can use base when you hide a base class member
public B()
{
Type = "test";
Code = "nothing";
Access = "success";
//Cannot Access 'Name' Here as it is private
}
}
}

Resources