I want to use the following linq search, but to modify it so it will also search in users and admins.
NAME
, ID
and PASS
are strings given for compare. If all 3 match, then the program knows what kind of user it is, admin or user, and moves from there. Otherwise, he isn't in any list and an error will show.
XElement xelement = XElement.Load(@"c:\user.xml");
IEnumerable<XElement> users = xelement.Elements();
foreach (var user in users)
{
if((user.Element("Id").Value==ID)&&(user.Element("Username").Value==NAME)&&(user.Element("Password").Value==PASS))
}
The xml file is built like this:
<Data>
<UserList>
<User Id="123" Username="abc" Password="abc123"></User>
</UserList>
<AdminList>
<Admin Id="123" Username="abc" Password="abc123"></Admin>
</AdminList>
</Data>
Your current code uses LINQ to XML classes, but you don't actually use any LINQ queries.
What you can do is:
Get admins and users separately
XDocument xDoc = XDocument.Load(@"c:\\user.xml"); var admins = xDoc.Root.Element("AdminList").Elements("Admin"); var users = xDoc.Root.Element("UserList").Elements("User");
Concatenate them together:
var adminsAndUsers = admins.Select(x => new { Element = x, Type = "Admin" }) .Concat(users.Select(x => new { Element = x, Type = "User" }));
Query result collection looking for matching user. I used (string)XAttribute
casting instead of XAttribute.Value
property, because it's more safe to use (won't throw an exception when attribute does not exist).
var user = adminsAndUsers.FirstOrDefault( x => (string)x.Element.Attribute("Id") == ID && (string)x.Element.Attribute("Username") == NAME && (string)x.Element.Attribute("Password") == PASS);
Check query results
if(user != null) { // user is there var type = user.Type; } else { // no user matches }
try this solution
structure
public struct test
{
public bool isStudent;
public string id;
public string Username;
public string Password;
}
List<test> users = doc.Descendants("User").Where(e => e.Attribute("Id").Value == "123").Select(e => new test{ isStudent = true, id = e.Attribute("Id").Value, Username = e.Attribute("Username").Value, Password = e.Attribute("Username").Value }).ToList();
List<test> admins = doc.Descendants("Admin").Where(e => e.Attribute("Id").Value == "123").Select(e => new test { isStudent = false, id = e.Attribute("Id").Value, Username = e.Attribute("Username").Value, Password = e.Attribute("Username").Value }).ToList();
List<test> allTogether = users.Concat(admins).ToList();
foreach (var xElement in allTogether)
{
//check if xElement property isStudent is true
}
now in allTogether list you can check avery property that you need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.