ok so this is maybe very simple but I just can not see where I am going wrong so any help is grateful
I have a model of this:
public IEnumerable<SelectedProfiels> profiles { get; set; }
public class SelectedProfiels
{
public int Identifer { get; set; }
public string ProfileName { get; set; }
}
and then I am trying to read from this
i am then building an array called selectedProfiles,
I then have this code
var pro = from s in selectedProfiles select s;
What im wanting to do is find all the ProfileName's and assigned them there on ViewBag.[i] or just there own string variable
I have a model collection like this
var userd = new User()
{
ID = i.FirstOrDefault(),
Type = t.FirstOrDefault(),
AuthorityLevel = a.FirstOrDefault(),
Language = l.FirstOrDefault(),
Profiles = pro,
};
public IEnumerable<SelectedProfiels> profiles { get; set; }
public class SelectedProfiels
{
public int Identifer { get; set; }
public string ProfileName { get; set; }
}
I then pass userd to a new page:
return RedirectToAction("test", "Account", userd);
public ActionResult test (Userm)
{
ViewBag.d = m.profiles;
return View();
}
any help please
So, given your linq query:
var pro = from s in
selectedProfiles
select s;
You can use Linq to generate an IEnumerable from pro, like:
var selectedProfiles = pro.Select(p => p.ProfileName).ToList();
Then, you can use selectedProfiles to populate the array you desire:
string[] newStrings = selectedProfiles.ToArray();
Instead of
select s
Just use
select s.ProfileName
Related
I have a list created from a stored procedure using EF6.0
I have also created 3 classes
public class Resas
{
public string todo{ get; set; }
public string prop { get; set; }
public string Code { get; set; }
public string statusCode { get; set; }
public string checkin { get; set; }
public string checkout { get; set; }
public List<profiles> profiles { get; set; }
}
public class profiles
{
public string action { get; set; }
public string id { get; set; }
public string profileType { get; set; }
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public List<emailAddresses> emailAdresses { get; set; }
}
public class emailAddresses
{
public string emailAddress { get; set; }
public string emailAddress2 { get; set; }
}
I am doing a for-loop in the list and I need to get certain columns and put it in the array (I will put two, to keep it simple)
myEntities db = new myEntities();
List<rev_Result> revList = new List<rev_Result>();
revList.Clear();
revList = db.rev().ToList();
for (int i = 0; i < revList.Count(); i++)
{
Resas resas = new Resas();
profiles[] profiles = new profiles[1];
resas.todo = revList[i].todo;
resas.profiles[0].lastName = revList[i].lastName;
}
I am not familiar with C# as you can see from the psedo-code above.
I cannot figure out how to feed the Resas with data and then its Profile with data and then move to the next Resas entry.
Any help appreciated.
That's fairly simple using Linq:
Resas resas = new Resas();
resas.profiles = revList
.Select(x => new profiles() { action = x.todo, lastName = x.lastName })
.ToList();
What's happening here is: You loop through every entry in revList and get your wanted data structure (that's what Select is doing). x refers to the current entry in the loop, while the stuff to the right side of the arrow is you 'output': a new instance of your profiles class with the members assigned accordingly. The result of all of this is then converted to a list (before ToList(), think of it as a recipe to create the list) and assigned to resas.profiles.
By the way, a word on conventions: Usually, in C#, you would give your classes a name that starts with a capital letter. Also, your profiles class seems to contain data of exactly one profile, so a better name might be Profile. This also makes your data structure more clear, since List<profiles> seems to be a list of lists of profiles - but that's not what it actually is, is it?
Furthermore, Members generally start with a capital letter as well, so instead of action, lastName, you'd have: Action and LastName.
You can try with Linq. This is the code that should solve your issue, but Resas class doesn't have action property:
List<Resas> ls = revList.Select(x => new Resas() {
action = x.todo,
profiles = new List<profiles>() {
new profiles { lastName = x.lastName }
}
).ToList();
If you need to use action property of inprofiles` class:
List<Resas> ls = revList.Select(x => new Resas() {
profiles = new List<profiles>() {
new profiles {
action = x.todo,
lastName = x.lastName
}
}
).ToList();
This is my first question on SO, please let me know if I am doing anything wrong!
I am trying to parse an XML similar to this:
<LiveUpdate>
<CityID>F0A21EA2</CityID>
<CityName>CityTown</CityName>
<UserName>john</UserName>
<ApplicationDetails>
<ApplicationDetail
Application="AC"
Licensed="true"
Version="2015.2"
Patch="0001"
/>
<ApplicationDetail
Application="AP"
Licensed="true"
Version="2015.2"
Patch="0002"
/>
</ApplicationDetails>
</LiveUpdate>
I have classes that look like this:
public class Client
{
public string cityID { get; set; }
public string cityName { get; set; }
public string userName { get; set; }
public List<Apps> appList { get; set; }
}
public class Apps
{
public string app { get; set; }
public string licensed { get; set; }
public string version { get; set; }
public string patch { get; set; }
}
I need to be able to have a client class with a list of all the application details to be iterated over.
So far the best I've come up with is:
XDocument xml = XDocument.Load(#"C:\blah\Desktop\1.xml");
var liveUpdate = xml.Root;
var clients = (from e in liveUpdate.Elements()
select new Client()
{
cityID = e.Element("CityID").Value,
cityName = e.Element("CityName").Value,
userName = e.Element("UserName").Value,
appList = e.Elements("ApplicationDetails")
.Select(a => new Apps()
{
app = a.Element("Application").Value,
licensed = a.Element("Licensed").Value,
version = a.Element("Version").Value,
patch = a.Element("Patch").Value
}).ToList()
});
However, I'm currently running into an error that says Object reference not set to an instance of an object.
I've seen some similar examples on here, but not that deal with data before the multiple children.
I'm fairly new to XML and Linq so any help here would be greatly appreciated!
Your XML only contains one LiveUpdate tag, so rather than iterating over all of the elements inside of it, you just want to look at the Root element.
In ApplicationDetails, Application, Licensed and such are attributes, not elements. Use .Attribute() to access them.
ApplicationDetails is a single tag, and inside it you have ApplicationDetail tags.
There is no DateTime element in your LiveUpdate tag.
This works:
var liveUpdate = xml.Root;
var e = liveUpdate;
var clients = new Client()
{
cityID = e.Element("CityID").Value,
cityName = e.Element("CityName").Value,
userName = e.Element("UserName").Value,
//dateTime = e.Element("DateTime").Value,
appList = e.Element("ApplicationDetails").Elements("ApplicationDetail")
.Select(a => new Apps()
{
app = a.Attribute("Application").Value,
licensed = a.Attribute("Licensed").Value,
version = a.Attribute("Version").Value,
patch = a.Attribute("Patch").Value
}).ToList()
};
Since you have already defined a class into which you wish to deserialize, you can use XmlSerializer to deserialize it for you.
First, let's rename some of your property names to more closely match the XML and c# naming conventions:
[XmlRoot("LiveUpdate")]
public class Client
{
public string CityID { get; set; }
public string CityName { get; set; }
public string UserName { get; set; }
[XmlArray("ApplicationDetails")]
[XmlArrayItem("ApplicationDetail")]
public List<Apps> AppList { get; set; }
}
public class Apps
{
[XmlAttribute]
public string Application { get; set; }
[XmlAttribute]
public bool Licensed { get; set; }
[XmlAttribute]
public string Version { get; set; }
[XmlAttribute]
public string Patch { get; set; }
}
Then add the following extension methods:
public static class XmlSerializationHelper
{
public static T LoadFromXML<T>(this string xmlString)
{
using (StringReader reader = new StringReader(xmlString))
{
object result = new XmlSerializer(typeof(T)).Deserialize(reader);
if (result is T)
{
return (T)result;
}
}
return default(T);
}
public static T LoadFromFile<T>(string filename)
{
using (var fs = new FileStream(filename, FileMode.Open))
{
object result = new XmlSerializer(typeof(T)).Deserialize(fs);
if (result is T)
{
return (T)result;
}
}
return default(T);
}
}
Now you can deserialize from your XML file as follows:
string fileName = #"C:\blah\Desktop\1.xml";
var client = XmlSerializationHelper.LoadFromFile<Client>(fileName);
I manually updated your Client class to map correctly to the provided XML, but if you wanted to do it automatically, see here: Generate C# class from XML.
I want to use ExecuteQuery() to get IEnumerable of type Entities.UserLevel. Following code works well.
using (CDataContext context = data.GetDataContext())
{
string q = "SELECT *FROM UserLevel";
IEnumerable<Entities.UserLevel> res = context.ExecuteQuery<Entities.UserLevel>(q);
}
public class UserLevel
{
public int userID { get; set; }
public int levID { get; set; }
}
But the problem is that I must use property names in UserLevel class same as in database, otherwise I do not get values. I wonder is there any way to get values irrespective of class/property name? For example, I want to use following UserLevel class instead of above:
public class UserLevel
{
public int UserIdentity { get; set; }
public int LevelIdentity { get; set; }
}
Sure just write.
var q = "SELECT userID as UserIdentity, levID as LevelIdentity FROM UserLevel";
var res = context.ExecuteQuery<UserLevelDTO>(q);
But why not use Linq instead? You could write:
var res = from u in context.UserLevel
select new UserLevelDTO()
{
UserIdentity = u.userID,
LevelIdentity = u.levID
};
You would need to create your own DTO class.
public class UserLevelDTO
{
public int UserIdentity { get; set; }
public int LevelIdentity { get; set; }
}
I need to add data to view model using LINQ
My view model is :
public class SearchScrapViewModel
{
public WClass wClass{get; set;}
public SClass sClass{get; set;}
public YClass yClass { get; set; }
}
public class WClass
{
public string title { get; set; }
public string link { get; set; }
}
public class SClass
{
public string title { get; set; }
public string link { get; set; }
}
public class YClass
{
public string title { get; set; }
public string link { get; set; }
}
and i need to use these 3 classes with 3 different LINQ query and then pass data to return View(SearchScrapViewModel);
var wikians = //LINQ Logic
select new SearchScrapViewModel
{
wClass.link = link.Attributes["href"].Value, //Error: I am not able to add to wClass
wClass.title = link.InnerText
};
and similarly to other classes
and then pass to return View(SearchScrapViewModel); so that i can access all the 3 classes in View of this controller
How to do that?
You forgot to create an instance of your WClass:
select new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
Alternatively, you could make WClass (and SClass and YClass) a struct instead of a class, then you don't need to instantiate it. In that case, however, you should probably make the struct immutable.
LINQ is not the be-all-end-all, and I dont know that this is the best approach for what you are looking for. I would suggest looking at the Builder Pattern, to accomplish this. If you really want to, you could do this in one LINQ query (using object initializers), but it might not read as clean as a builder would (but that is my two cents):
select new SearchScrapViewModel
{
wClass = new wClass{title = xyz, link = xyz},
sClass = new sClass...
yClass = new yClass...
}
It is not clear to me why you need a select statement in your example. In any case you can't return SearchScrapViewModel as your return because that is a type and not the instance. Unless your code is simplified for this post and you do need linq, I would suggest:
var wikians =
new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
return View(wikians);
I have the following classes:
public class Menu
{
public int Order { get; set; }
public string Title { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public bool Default { get; set; }
public string Link { get; set; }
public string Notes { get; set; }
public string Text { get; set; }
}
public class MenuItem
{
public int Order { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public bool Default { get; set; }
public string Link { get; set; }
}
Also this which returns ICollection
var menu = _menuRepository.GetPk(pk);
Can someone show me how I can use LINQ to:
a) Get the data from menu
b) Select only rows where Status = "00"
c) Order by Order
d) Put the data into the MenuItem class
I heard there are maybe two ways of coding this. Can anyone explain these and advise which would be better.
Try this:
var menuItems = _menuRepository.GetPk(pk)
.Where(m => m.Status == "00")
.OrderBy(m => m.Order)
.Select(m => new MenuItem
{
Order = m.Order,
Title = m.Title,
Type = m.Type,
Default = m.Default,
Link = m.Link
});
You can throw .ToList() at the end to materialize collection immediately.
Jimmy's answer looks right to me - here's the equivalent in query expression form:
var query = from m in _menuRepoistory.GetPk(pk)
where m.Status == ""
order by m.Order
select new MenuItem
{
Order = m.Order, Title = m.Title, Type = m.Type,
Default = m.Default, Link = m.Link
};
You might want to consider adding a MenuItem constructor which takes a Menu, or a ToMenuItem method to Menu, so you could just use:
var query = from m in _menuRepoistory.GetPk(pk)
where m.Status == ""
order by m.Order
select m.ToMenuItem();
(As with Jimmy's answer, you can call ToList to materialize the results in a List<T>.)