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.
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 list of type Notification. I also have a type of NotificationWithScore.
Notification With Score looks like:
public class NotificationWithScore
{
public Notification Notification { get; set; }
public int Score { get; set; }
}
I want to create a new list of type NotificationWithScore using the existing notification list I already have and provide a default score of 0.
when I go to create a List<NotificationWithScore> n = new List<NotificationWithScore>();
I can only assign them individually using a foreach. Is there a way to do this in Linq?
Use LINQ
List<NotificationWithScore> AddScore(List<Notification> list)
{
return list.Select(n => new NotificationWithScore { Notification = n, Score = 0 }).ToList();
}
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();
I want to retrieve all tickets whose badge number is present in the list
i have a listA
public class Li
{
public string s { get; set; }
public string t { get; set; }
public string b { get; set; }
}
i have a method
i try this condition but it doesn't work,
doesn't recognize tostring for the first and doesn't recognize the list
Any idea how solve my problem?
This should work:
where listeLigneXls.Select(lgn => lgn.badge).Contains(chb.NUM_BADGE)
Need to change in this code block
where listeLigneXls.Select(lgn =>lgn.badge).Contains(chb.NUM_BADGE)
Contain is extension method of list of primitive data type
I change the method I get the values of the badge number and I would like to use it in my second query but I do not know how
I created the following:
public class HttpStatusErrors
{
public HttpStatusErrors()
{
this.Details = new List<HttpStatusErrorDetails>();
}
public string Header { set; get; }
public IList<HttpStatusErrorDetails> Details { set; get; }
}
public class HttpStatusErrorDetails
{
public HttpStatusErrorDetails()
{
this.Errors = new List<string>();
}
public string Error { set; get; }
public IList<string> Errors { set; get; }
}
In my code I am using it like this:
var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
foreach (var eve in ex.EntityValidationErrors) {
msg.Details. // Valid so far
msg.Details.Error // Gives the error below:
The Ide recognizes msg.Details as being valid but when I try to write the second line I get:
Error 3 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>'
does not contain a definition for 'Error' and no extension method 'Error' accepting a first
argument of type 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>'
could be found (are you missing a using directive or an assembly reference?)
C:\K\ST136 Aug 16\WebUx\Controllers\ProblemController.cs 121 33 WebUx
Is there something I am doing wrong? I thought the way I had this set up that new Lists would be created when the first class was created.
msg.Details returns a List object. List<T> does not have an Errors property. You need to access a specific element in your list, and only then will you have your Errors property.
For example:
msg.Details[0].Error
In your code you might want to make sure that msg.Details contains elements before trying to access them, or better yet iterate over them in a foreach loop.
Details is a collection. The property Error belongs to an item in the collection Details. There is no property Error on that collection Details
you are tying to go to Details which is a IList<HttpStatusErrorDetails>.
if you want to go through the items in that list u need go over them
for example
msg.Details[number].Errors
or
foreach(HttpStatusErrorDetails err in msg.Details)
{
err.Errors
}