问题
Can anyone help with a problem i have, im trying to write a method that will return a list of my DTO objects
I am getting the user by the usrCode and and the getting a list of their jobCodes in the DB. Then i am getting a list of All Jobs from WCF. I then want to make a new list with the jobDescription attached the DTO as the DB only has userCode and jobCode. What i want is a list of JobDescription from my WCF but from a list of Jobs a user DOESNT have. via this....
List<UserJobsDTO> list = listBuilder(jobs, yetToHave);
Currently i have only this, i have managed to get a list of jobCodes a user doesnt have but i need jobDescriptions... Can anyone help me complete my method?
public ActionResult addJob(string usrCode)
{
var jobs = jobsClient.GetAlljobs();
var alljobsCode = (from s in jobs select s.jobsCode).ToList();
var thisUserJobCode = (from s in db.UserJobs
where s.usrCode == usrCode
select s.jobsCode).ToList();
var yetToHave = alljobsCode.Except(thisUserJobCode);
List<UserJobsDTO> list = listBuilder(jobs, yetToHave);
ViewBag.jobsCode = new SelectList(list, "jobsCode", "jobDescription");
var model = new UserJob { usrCode = usrCode };
return View("addJob", model);
}
private List<UserJobsDTO> listBuilder(jobsService.jobsDTO[] jobs, IEnumerable<string> yetToHave)
{
foreach (string s in yetToHave)
{
for every yetToHave job
attach description to UserJobsDTO.Description
}
}
DTO:
public class UserJobsDTO
{
public String userCode { get; set; }
public String jobsCode { get; set; }
public String jobDescription { get; set; }
}
回答1:
You can use the LINQ Contains
method with !
( That means not contains)
Assuming jobsClient.GetAlljobs()
returns a collection of UserJobsDTO
DTO.
//Get all Jobs
var allJobs = jobsClient.GetAlljobs().ToList();
//Get a list of Job code this user
var thisUsersJobCodeList = (from s in db.UserJobs where s.usrCode == usrCode
select s.jobsCode).ToList();
//Get items from all jobs except the items in thisUsersJobCodeList
var yetToHave = allJobs.Where(s => !thisUsersJobCodeList .Contains(s.jobsCode)).ToList();
//Convert to a List<SelectListItem> for dropdown
var dropDownData = yetToHave.Select(s => new SelectListItem
{ Value = s.jobsCode, Text = s.jobDescription}).ToList();
ViewBag.jobsCode = dropDownData;
来源:https://stackoverflow.com/questions/34966533/iterate-though-ienumerablestring-to-populate-listdto-mvc-c-sharp