If I have a string result="Out of Service" .And I want to update it to its short form if it matches with full name by comparing with a list that has values like attached image :
How can I do that?
Using Linq
var result = "Out of Service";
result = shortForms.FirstOrDefault(model => model.Name == result)?.ShortName ?? result;
I am new in the MongoDB world and now I am struggling of how can I delete, update element in a nested array field of a document. Here is my sample document:
{
"_id" : ObjectId("55f354533dd61e5004ca5208"),
"Name" : "Hand made products for real!",
"Description" : "Products all made by hand",
"Products" : [
{
"Identifier" : "170220151653",
"Price" : 20.5,
"Name" : "Leather bracelet",
"Description" : "The bracelet was made by hand",
"ImageUrl" : "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQii6JCvXtx0iJGWgpvSl-KrdZONKYzDwS0U8uDvUunjO6BO9Aj"
}
]
}
In my method, I get the id of the document and the id(Identifier) of the Product that I want to delete. Can anyone tell me how can I delete from the Products field the element having Identifier: 170220151653?
I tried:
var query = Query.And(Query.EQ("_id", categoryId), Query.EQ("Products.Identifier", productId));
var update = Update.Pull("Products", new BsonDocument() { { "Identifier", productId } });
myDb.Applications().Update(query, update);
as suggested here: MongoDB remove a subdocument document from a subdocument
But I get an error at
myDb.Applications()
It just can't be found.
SOLVED:
var pull = Update<Category>.Pull(x => x.Products, builder => builder.EQ(q => q.Identifier, productId));
collection.Update(Query.And(Query.EQ("_id", ObjectId.Parse(categoryId)), Query.EQ("Products.Identifier", productId)), pull);
You are calling method Pull(string name, MongoDB.Bson.BsonValue value) and according to the docs it
Removes all values from the named array element that are equal to some
value (see $pull)
and you provide { "Identifier", productId } as the value. I guess that mongo does not find that exact value.
Try to use the second overload of Pull with query-condition instead of exact value
Removes all values from the named array element that match some query
(see $pull).
var update = Update.Pull("Products", Query.EQ("Identifier", productId));
UPDATE
Since you mention Category entity so I can suggest using lambda instead of
Query.EQ:
var pull = Update<Category>.Pull(x => x.Products, builder =>
builder.Where(q => q.Identifier == productId));
Solution with C# MongoDB Driver. Delete a single nested element.
var filter = Builders<YourModel>.Filter.Where(ym => ym.Id == ymId);
var update = Builders<YourModel>.Update.PullFilter(ym => ym.NestedItems, Builders<NestedModel>.Filter.Where(nm => nm.Id == nestedItemId));
_repository.Update(filter, update);
I was also facing the same problem and then finally after doing lot of R&D, I came to know that, you have to use PullFilter instead of Pull when you want to delete using filter.
I had the same of deleting elements from the nested array but after research, I found this piece of working code.
var update = Builders<Category>.Update.PullFilter(y => y.Products, builder => builder.Identifier== productId);
var result = await _context.Category.UpdateOneAsync(filter, update);
return result.IsAcknowledged && result.ModifiedCount > 0;
Hi as per my understanding you want to remove whole matched elements of given id and identifier so below query will solve your problem but I don't know how to convert this into C#, here mongo $pull method used.
db.collectionName.update({"_id" : ObjectId("55f354533dd61e5004ca5208")}, {"$pull":{"Products":{"Identifier":"170220151653"}}})
Solution for C# MongoDB Driver. You can set empty [] the nested array.
var filter = Builders<MyUser>.Filter.Where(mu => mu.Id == "my user id");
var update = Builders<MyUser>.Update.Set(mu => mu.Phones, new List<Phone>());
_repository.Update(filter, update);
I have PHP code
$records = array(
array('myobjecttype' => array('field1' => 'value', 'field2' => 'value')),
array('myotherobjecttype' => array('field1' => 'value', 'field2' => 'value'))
);
I am working on converting php code to C#. Above php code is used later to loop through and create xml where each array is Node in xml.
I need similar data structure in c# which can do the same task. Kindly guide me.
Pavan
Why not create a proper class with properties and create a list of them?
public class Record
{
public string Field1{get;set;}
public string Field2{get;set;}
}
And then in your method you do the following:
var recordA = new Record{Field1 = "Value 1", Field2 = "Value 2"};
var recordB = new Record{Field1 = "Value 1", Field2 = "Value 2"};
var records = new List<Record>{recordA, recordB};
UPDATE
You obviously want to define the Record properties with a proper names like Title, ReleaseDate etc. and give them types like int, DateTime etc.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use LINQ to read all nodes from XML
I am trying to read an XML file using Linq in C# windows application. The sample of the xml string is given below.
<Root>
<Name>John Doe</Name>
<Data>FBCCF14D504B7B2DBCB5A5BDA75BD93B</Data>
<customer>true</customer>
<Accounts>1</Accounts>
<dataSet>
<Type1>Found matching records.</Type1>
<Type2>No matches found.</Type2>
<Type3>Found matching records.</Type3>
</dataSet>
</Root>
I want to display all the data inside the <dataset> tag and <datatag> i want to read <customer> tag as well.
I have created a class with members (string type, string status). Where in type i want to store the type1, 2...and in status i want to store what is inside the type node.
I am able to accomplish this but in the code i have to give
type1 = (string)row.Element("type1"),
type2=(string)row.Element("type2"),
i want to have a generic code in which i dont have to mention every type. In other words i want to read all the child nodes of tag whithout mentioning the tag name. I have spent 2 hours searching for this on google, but haven't found anything yet.
Expected output
save the information in class object (type and status).
And i want to read the customer tag so that i can know whether the person is already a customer
Any help will be very much appreciated.
Thanks
Update
According to inputs received from Raphaƫl Althaus
I have the following code:
var list = xml.Descendants("dataSet").Elements()
.Select(m => new CustomerInfo
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
foreach (CustomerInfo item in list)
{
MessageBox.Show(item.Type+ " "+item.Value);
}
and for reading the Customer tag i have written more code.
var isCustomer = from customer in xmlDoc.Descendants("Root")
select new
{
customer = tutorial.Element("customer").Value,
}
Can i do both in one query?. Or this method is not so heavy on performance, so i can use this?
something like that ?
var q = xml.Descendants("dataSet").Elements()
.Select(m => new
{
type = m.Name.LocalName,
value = m.Value
}).ToList();
You can also directly populate a list of your "class with members"
var list = xml.Descendants("dataSet").Elements()
.Select(m => new <TheNameOfYourClass>
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
EDIT :
to get the "customer" value, I would do another query
var customerElement = xml.Element("customer");
var isCustomer = customerElement != null && customerElement.Value == "true";
So you could mix all of that it in a little function
public IList<YourClass> ParseCustomers(string xmlPath, out isCustomer) {
var xml = XElement.Load(xmlPath);
var customerElement = xml.Element("customer");
isCustomer = customerElement != null && customerElement.Value == "true";
return xml.Descendants("dataSet").Elements()
.Select(m => new <YourClass>
{
Type = m.Name.LocalName,
Value = m.Value
}).ToList();
}
I am using an xml file from this link..
http://www.goalserve.com/samples/soccer_livescore.xml
..
Lets say "category" is our "Tournament" then
I need to search and show the ---
1. The listing of all the "Tournaments" in gridview or datalist.
2. The listing of matches within a selected "Tournament"..
3. The listing of events within the matches etc..
Pls guide me how to achieve this... M using a Dataset.Readxml but then the inner linking of fields become very complex...
Pls guide...
Thanks..n..regards,
The simplest way to do this is with LINQ to XML. Something like this:
var doc = XDocument.Load(url);
var tournaments = doc.Root
.Elements("category")
.Where(x => (string) x.Attribute("name") == "Tournament")
.Single(); // Is there only one matching catgeory?
var matches = tournaments
.Elements("match")
.Select(m => new
{
LocalTeam = (string) m.Element("localteam").Attribute("name"),
VisitorTeam = (string) m.Element("localteam").Attribute("name"),
Events = m.Elements("Events")
.Select(e => new
{
Player = (string) e.Attribute("player"),
Type = (string) e.Attribute("type"),
// etc
})
.ToList();
});
How you display that is then up to you. You may want to create your own "normal" types for Event, Match etc rather than using the anonymous types above.
LINQ to XML is by far the simplest way of working with XML that I've used.