public class Role
{
public string RoleName { get; set; }
public int RoleId { get; set; }
public Role(int roleid, string roleName)
{
RoleName = roleName;
RoleId = roleid;
}
}
public class RoleManagement
{
public List<Role> RoleList = new List<Role>();
RoleList.Add(1, "Software Engineer");
}
I am trying to add some values to the list
I am facing a errors such as
Type Expected
Tuple must contain atleast two elements
How can i add some elements into the list
You need to construct the Role object first, you can not add constructor parameters directly to the list:
RoleList.Add(new Role(1, "Software Engineer"));
Edit:
RoleList is an object of type List<Role>, in other words it's a List of objects of type Role. The Add method requires a single parameter, which should have the type Role (or derived). When calling RoleList.Add(1, "Software Engineer") you pass two parameters - of type int and string, while the method Add only accepts one: List<Role>.Add(Role item). In which case you should be getting compiler error CS1501 No overload for method 'Add' takes 2 arguments.
To construct a Role object you must use the new keyword and provide constructor parameters if required: new Role(1, "Software Engineer").
Related
These are my classes:
public class Registration
{
public bool? IsRegistered { get; set; }
public List<RegistrationProcess> RegistrationProcess { get; set; }
}
public class RegistrationProcess
{
public bool? PaidInFull { get; set; }
public double PaymentAmount { get; set; }
public bool IdentityVerified { get; set; }
}
I have a method that is doing the object mapping like this:
public Registration Translate(Services.Registration source)
{
return new Registration
{
IsRegistered = source.IsRegistered,
RegistrationProcess = new List<RegistrationProcess>
{
new RegistrationProcess()
{
PaidInFull = source.RegistrationProcess.Select(o => o.HasPaid),
}
}
};
}
I am not sure how to set up the mapping for the RegistrationProcess.
I want to map PaidInFull within RegistrationProcess to the property HasPaid. They are both bools.
I am getting an error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<bool?>' to 'bool?'
I feel like I need to add something to the end of the Select statement but I am not sure what. I did FirstOrDefault() and that made the error go away but I only got one value back and that is not what I want.
The problem with your approach is that you are only creating one instance of RegistrationProcess inside the list constructor. So by calling source.RegistrationProcess.Select(o => o.HasPaid) and assign it to your newly created RegistrationProcess you are creating a Collection of all bool values of your service registration process and try to assign it to a single registration process.
The Solution is to create multiple RegistrationProcess instances. In fact, one for each element in source.RegistrationProcess. To do this you can use the Select method on source.RegistrationProcess directly:
source.RegistrationProcesses.Select(x => new RegistrationProcess() { PaidInFull = x.HasPaid }).ToList()
As you can see, for every element in source.RegistrationProcesses a new RegistrationProcess is created. Or in other words: you select the elements of source.RegistrationProcesses as new RegistrationProcess() { PaidInFull = x.HasPaid } if that makes more sense to you.
The .ToList() converts the IEnumerable to a list.
I have following classes:
public class Selections
{
public List<Selection> selection { get; set; }
}
public class Selection
{
public Promotion promotion { get; set; }
public Products products { get; set; }
}
public class Products
{
public List<int> productId { get; set; }
}
I am creating List and assigning property values but when I am adding the list I'm getting error:
The best overloaded method match for
'System.Collections.Generic.List.Add(Selection)' has some
invalid arguments
C# code:
Selections productSelections = new Selections();
List<Selection> listOfProductSelections = new List<Selection>();
Selection dataSelection = new Selection()
{
promotion = new ProviderModels.Common.Promotion()
{
promotionID = Convert.ToInt32(applicablePromotion.PromotionId),
lineOfBusiness = applicablePromotion.LineOfBusiness
},
products = new ProviderModels.Common.Products()
{
productId = GetIdsOfSelectedProducts(context, selectedOffer)
}
};
productSelections.selection.Add(listOfProductSelections);
Am I missing something?
You are adding a list to another list. You want to add the list items.
Instead of
productSelections.selection.Add(listOfProductSelections);
write
productSelections.selection.AddRange(listOfProductSelections);
But you have to be sure you have initialized the selection property at that point, otherwise you'll run into a NullReferenceException.
By the way, check all your error messages. You will see a second message telling you which type is excpected and what you were using.
you should use AddRange as listOfProductSelections is a list.
productSelections.selection.AddRange(listOfProductSelections)
productSelections.selection is a reference to a List, consquently when you try to add an item to it (last line of your example) the Add method expects a parameter of type of Selection - you're passing listOfProductSelections which is a reference to another list.
Maybe you wanted to add dataSelection which is of the required type? If not, you can use AddRange as the other respondents have suggested.
I am using generic method to fill my dropdown for all types
below is my code.
the entity type are as follow
public class Role
{
public string Id { get; set; }
public string Name { get; set; }
}
public class DropDown
{
public string Id { get; set; }
public string Name { get; set; }
}
i am able to fetch data successfully at
var data = DataFetcher.FetchData<T>();
private static void Main( string[] args )
{
List<DropDown> cities = BLL.GetDataList<City>();
List<DropDown> states = BLL.GetDataList<State>();
List<DropDown> roles = BLL.GetDataList<Role>();
}
public static class BLL
{
public static List<DropDown> GetDataList<T>() where T : class ,new()
{
var data = DataFetcher.FetchData<T>();
return data as List<DropDown>;
}
}
I knew this cast data as List<DropDown> will fail,thats why its returning null back to calling method,
How can i cast Generic list to List of Known Type?
You have to ask yourself: how do I want to convert T to DropDown? If you can't answer this, the answer is: you can't.
I guess your DropDown class has an object Value property, that holds the dropdown value, and you wish to assign the data entity to that property.
Then you can project the list of data entities to DropDowns as such:
var data = DataFetcher.FetchData<T>();
return data.Select(d => new DropDown { Value = d }).ToList();
As for your edit: so you have at least one type, the displayed Role, that has an Id and Name property. But type T doesn't guarantee this, so you'd need to introduce an interface:
public interface INamedIdentifyableEntity
{
string Id { get; set; }
string Name { get; set; }
}
And apply this to your entities. Then introduce it as a generic constraint and do the mapping:
return data.Select(d => new DropDown
{
Id = d.Id,
Name = d.Name,
}).ToList();
But you don't want this, as here you are tying these two properties to dropdowns. Tomorrow you'll want an entity with Code instead of Id and Text instead of Name, so you'll have to add more interfaces, more overloads, and so on.
Instead you might want to use reflection, where you can specify the member names in the call:
List<DropDown> cities = BLL.GetDataList<City>(valueMember: c => c.CityCode, displayMember: c => c.FullCityname);
And use these member expressions to look up data's values and fill those into the DropDown.
However, you're then reinventing the wheel. Leave out your DropDown class entirely, and leave the dropdown generation to the front end, in this case MVC:
var cities = DataFetcher.FetchData<City>();
var selectList = new SelectList(cities.Select(c => new SelectListItem
{
Selected = (c.Id == selectedCityId),
Text = c.FullCityName,
Value = c.CityCode,
});
Or:
var selectList = new SelectList(cities, "CityCode" , "FullCityName", selectedCityId);
One solution is to use AutoMapper.
First create a map between your models like this:
AutoMapper.Mapper.CreateMap<Role, DropDown>();
Do the same thing for City and State classes if you need to.
Then you can use AutpMapper to convert your objects to DropDown like this:
public static List<DropDown> GetDataList<T>() where T : class ,new()
{
var data = DataFetcher.FetchData<T>();
return data.Select(x => AutoMapper.Mapper.Map<DropDown>(x)).ToList();
}
If I understood the question correctly, you could use Linq as follows.
return data.Cast<DropDown>().ToList();
Long Description: I'm writing a basic search by filter function from an entity, so I can do something like this:
public Entity GetEntityBy(Entity filter)
{ }
public IList<Entity> GetEntitiesBy(Entity filter)
{ }
The problem is with non nullable types (int, float, etc), and I don't want to "force" all properties to be written as nullables. I want to avoid any kinds of rules (such as applying attributes or implementing my own get/set) so I can write the entity just as usual and simply use this filter function.
The code looks like this:
public class Entity
{
public int EntityID { get; set; }
public string Name { get; set; }
public DateTime RegisterDate { get; set; }
//Other properties
}
public IList<Entity> GetEntitiesBy(Entity filter)
{
if (filter != null)
{
if (filter.EntityID > 0)
{
//Add criteria to filter by ID
//In this case it works because there shouldn't have any IDs with 0
}
//this won't work because DateTime can't be null
//I can't check the default value as well because there are some searchs using the default value and I don't want to ignore that
if (RegisterDate != null)
{
}
}
}
It's supposed to be a simple equal filter depending on the values found in the filter parameter, but as it is now I don't know when I should ignore the default values or not.
I already have a SCRUD manager sort of class, so I want to add a function call to the class that it belongs so I can check when a property has been read/written to.
Short Description: How do I add a function call before a property's get or set acessor is called on a dynamic class? Is this even possible?
I'm not sure if this is possible, or even how to properly word this.
I am creating a new webAPI that I want to use with an offline app. The app connects to the api (before going offline) and pulls down a list of fields to generate a dynamic form. I want to supply a list of fields to the client. In simple terms this might be id and description.
However, to generate the form exactly as I want it, I might want to supply a field "type" such as System.DateTime or System.String. Is it possible to do this?
In pseudocode this might be:
public class EntityType
{
public Guid EntityTypeId { get; set; }
public string Description { get; set; }
public Object Type { get; set; }
}
I might then want to create an EntityType like this:
EntityType entityType = new EntityType {
EntityTypeId = Guid.NewGuid(),
Description = "Visit Date",
Type = System.DateTime
};
It's the Type = System.DateTime I want to be able to achieve. I can then have my form generate a field where the type is date. The same might apply for strings for example.
To represent a type, use Type:
public Type Type { get; set; }
...
Type = typeof(DateTime)
However! It is unlikely that this will work with webapi, since Type is not interchangeable between platforms.
Another option is an enum of your expected types; you might find that TypeCode has everything you want, but you could also simply create your own enum of known types.