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 years ago.
Improve this question
I have a collection defined by:
public class CompanyModel
{
public int compnSN { get; set; }
public string compnName { get; set; }
public string compnAddress { get; set; }
}
How can I get out two set compnName and compnAddress together so that I can use each of that pair value one by one in a foreach loop ?
I tried:
var pairs = from companies
select new {name = companies.compnName, addr = companies.compnAddress}
foreach (var item in pairs)
{
//do some things with item.name;
//do some things with item.addr;
}
I know this idea can be executed but is my grammar wrong somewhere?
Try this one:
var result = companies.Select(x => new
{
Name = x.compnName,
Address = x.compnAddress
});
or this one:
var result = from company in companies
select new
{
Name = x.compnName,
Address = x.compnAddress
};
Then as you already pointed out:
foreach(var company in result)
{
// access the name like company.Name and do what you want.
// access the address like company.Address and do what you want.
}
UPDATE
The code you have posted has some grammatical errors. So despite the fact that your logic is correct, this piece of code will not be compiled.
Specifically, in the following piece of code:
var pairs = from companies
select new {name = companies.compnName, addr = companies.compnAddress}
you try to declare a local variable called companies that should belong in a collection.
Hence we should write this like below:
var pairs = from item in items
Now item is a local variable that refers to the random element in the collections called items. Then as you already have writen you will declare an anonymous type in the select clause:
var pairs = from item in items
select new
{
PropertyA = item.PropertyA
PropertyB = item.PropertyB
};
Related
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 3 years ago.
Improve this question
When Domain Model property Name gets data from the database it's a string "David,James", but I have created another View Model to convert that string into an array ["David","James"]. I have used my ViewModel in the read method now, now the ViewModel should read the Name property as ["David","James"]. I am not sure how to make it happen.
I would appreciate if anybody has any suggestion on how to make it happen.
Domain Model:
public class FullName
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Address {get; set;}
}
View Model:
public class NameViewModel
{
public Int32 Id { get; set; }
public List<string> Name { get; set; }
public String Address { get; set;}
}
Read Method:
public ActionResult Name_Read([DataSourceRequest]DataSourceRequest request)
{
try
{
DataSourceResult result = Identity.ToDataSourceResult(request, NameViewModel => new
{
Id = NameViewModel.Id,
Name = NameViewModel.Name ,
Address = NameViewModel.Address,
});
return Json(result);
}
I think you're looking for something like this:
DataSourceResult result = Identity.ToDataSourceResult(request, dataModel => new NameViewModel
{
Id = dataModel.Id,
Name = dataModel.Name.Split(","),
Address = dataModel.Address,
});
// typical delimiter characters
char[] delimiterChars = { ' ' };
// verify the name exists
if (!String.IsNullOrEmpty(name))
{
// Get the list of strings
string[] strings = name.Split(delimiterChars);
if (strings != null)
{
if (strings.Length == 1)
{
firstName = strings[0];
}
else if (strings.Length == 2)
{
firstName = strings[0];
lastName = strings[1];
}
else if (strings.Length == 3)
{
firstName = strings[0];
middleName = strings[1];
lastName = strings[2];
}
}
}
I am not at Visual Studio, but I think that is right.
When Domain Model property Name gets data from the database it's a string "David,James"
That is a terrible mistake in database Design. The ideal solution would be to fix the Backend Database to actually have two fields for those distinct values.
Failing that, the next step would be to try and split on the DB side. Many modern DBMS support Views, wich can have columns computed from actuall rows. That way you could avoid issues, like different code splitting the same input differently. And you could even henceforth treat it like it was always two Columns.
If you really want or need to it in code and given this exact input format, String.Split() can deal with this. Of coruse you can get fancier, and use stuff like Regular Expressions instead. But for this example, Split seems perfectly suiteable for the case.
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 6 years ago.
Improve this question
Class
public class AlldataPoints
{
public int phase{ get; set; }
public string recr{ get; set; }
public string study{ get; set; }
}
public class filter
{
public List<string> Phase;
public List<string> recr;
public List<string> study;
}
I have a list of above class say Alldatapoints 'lst' and an object of class filter 'obj'.
I want to filter only those rows of 'lst' that in which values of phases in 'obj' matches with 'lst' 'phases' and values of 'recr' in 'obj' matches 'recr' in 'lst' 'recr'. i want to use entity expression.
Use Contains on the list of filter arguments:
filter obj;
IEnumerable<AlldataPoints> lst;
var result = lst.Where(item => obj.Phase.Contains(item.phase) && obj.recr.Contains(item.recr));
Here you go:
public List<AlldataPoints> FilterPoinst(List<AlldataPoints> points, filter filter)
{
return points.Where(x => filter.Phase.Contains(x.phase)
&& filter.recr.Contains(x.recr)
&& filter.study.Contains(x.study)).ToList();
}
If you need to match ony one property then just replace && with || operator:
In your code just call this function:
var filter = new filter(); //init your filter
List<AlldataPoints> points = new List<AlldataPoints>(); // Here you should get your points
var filteredPoints = FilterPoinst(points, yourFilter); //you get your filtered points.
If this is a Linq-to-Entities query against your DbContext, you can still use Contains() to check if each value is in each corresponding list.
Once awkward thing is that you need to convert phase to a string, as it is an int and the list is a List<string>, but you cannot just use ToString(), you have to use SqlFunctions.StringConvert() - see this answer.
dbContext.AllDataPoints.Where(adp =>
filter.Phase.Contains(SqlFunctions.StringConvert((double)adp.phase).Trim())
&& filter.recr.Contains(adp.recr)
// && filter.study.Contains(adp.study)
)
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 6 years ago.
Improve this question
I will try to make clear my problem :
Let's assume that i have a coach company and my buses has a few different service lines.
My aim is to separately store data of services for per service in in a string array "string[]".
As my thought, the name of array must be consist of (Date time + service number)
The dream was to put all passenger and the number of sold coaches information into a string[]
For instance :
//** "2303201601" >>> day + month + year + service number
string[] "2303201601" = new string[44]; // of course doesn't work :P
so i tried my chance with the following code :
public static Array new_list (string name_list, int size)
{
string [] name_list = new string[size];
return name_list;
}
Please help me :D ?
Ok I think this is what you want, though your question is not clear. Build an object to hold all your data properly. Strings make bad objects
public class Bus
{
public Bus()
{
ServiceNumbers = new List<string>();
}
public DateTime Date {get; set;}
public int ServiceNumber {get; set;}
public List<string> ServiceNumbers {get; set;}
}
Now just use it
List<Bus> buses = new List<Bus>();
Bus busx = new Bus()
{
Date = new DateTime(year, month, day),
ServiceNumber = "X"
}
busx.ServiceNumbers.Add("servicenumberx");
buses.add(busx);
I'm presuming here that the string is just a storage mechanism and there is no special reason for it. i.e. you have another piece of technology that holds string only, etc.
You can use Dictionary. It will be like this:
var someVar=new Dictionary<string, string[]>();
someVar.Add("date+servnum", yourarray);
var yourArray = someVar["date+servnum"];
You can do this
public class service{
private string name;
private string[] info;
public service(string name,int size){ this.name=name; info=new string[size];
public getInfo(){ return info;}
}
And then, if you need an array of services you can do it:
List<services> allServices=new List<services>();
I do not know if I understand the problem correctly
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 6 years ago.
Improve this question
Is it possible in C# to carry out a loop to find the parent id for a particular page?
Here's the scenario: I'm developing a breadcrumb. For each page I need the parent Id, so I can use that to populate a list with a url and a page title.
1st page --- Parent page --- Grandparent page
I need to be able to do a loop to gather the parent id, then that will populate the list which goes through and finds the new parent page parent id (basically for the grandparent page) and then populates the list until there aren't any more.
At the moment the current page data is stored in var pageInSiteMap:
var overview = new List<PageDataModel>();
pageInSiteMap // A get command is used to place the data in here
if(pageInSiteMap != null && pageInSiteMap.ParentId.HasValue)
{
var parent = allpages.Data.Items.FirstOrDefault(x => x.Id == pageInSiteMap.ParentId
var parentEntry = new PageDataModel{
pageUrl = parent.Url, pageTitle = parent.Title
};
overview.Add(parentEntry);
}
I am going to take a stab at this and assume you need recursion, here is a quick example I wrote:
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public Page Parent { get; set; }
}
public class Class1
{
public List<Page> GetPages(Page currentPage)
{
var ret = new List<Page> {currentPage};
if(currentPage.Parent != null)
ret.AddRange(GetPages(currentPage.Parent));
return ret;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the specific items from the list of a model without using a foreach of the list? like if you return a List<model> holding a model with a few differnt items to specifically call those item.
If you want a list of a specific item that's within your list then you can use LINQ to return those items, for example:
var customerNames = customersList.Select(customer => customer.Name);
This would give you a string collection with all of your customer names equal to the amount that was in your original list.
Or if you would like to retrieve a number of different items from your model list then you may want to look into creating a class specifically for stripping out those items, for example:
public class CustomerContactDetails
{
public string Address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
...
var contactDetails = customersList.Select(customer => new CustomerContactDetails { Address = customer.Address, Email = customer.Email, Telephone = customer.Telephone });
You can use C# LambdaExpression, like this:
var yourModel = modelList.Where(x => x.Id = 12).Select(x).First();