Перепиши этот код на C# { pub fn new(name: &str) -> Self { Collection { name:…
- User
Перепиши этот код на C# { pub fn new(name: &str) -> Self { Collection { name: name.to_string(), documents: HashMap::new() } }
code - Assistant
Перепиши этот код на C# { pub fn new(name: &str) -> Self { Collection { name: name.to_string(), documents: HashMap::new() } }
pub fn iter(&self) -> impl Iterator<Item=&Document> {
self.documents.values()
}
pub fn add(&mut self, doc: Value) -> String {
let index = nanoid!();
let new_document = Document::new(doc, SystemTime::now());
self.documents.insert(index.clone(), new_document);
index
}
pub fn get(&self, index: &str) -> Option<&Document> {
self.documents.get(index)
}
pub fn get_all_documents(&self) -> Vec<&Document> {
self.documents.values().collect()
}
pub fn get_all_documents_iter(&self) -> impl Iterator<Item=&Document> {
self.documents.values()
}
pub fn get_document_by_id(&self, index: &str) -> Option<&Document> {
self.documents.get(index)
}
pub fn update_document(&mut self, index: &str, doc: Value) -> Result<(), DatabaseError> {
if let Some(existing) = self.documents.get_mut(index) {
existing.set_content(doc);
Ok(())
} else {
Err(DatabaseError::DocumentNotFound(index.to_string()))
}
}
pub fn remove(&mut self, index: &str) -> Result<Document, DatabaseError> {
self.documents.remove(index)
.ok_or_else(|| DatabaseError::DocumentNotFound(index.to_string()))
}
pub fn find(&self, query: &Value) -> Vec<&Document> {
self.documents.values()
.filter(|doc| self.matches_query(doc.content(), query))
.collect()
}
fn value_matches(&self, doc_value: &Value, query_value: &Value) -> bool {
match (doc_value, query_value) {
(Value::Object(doc_obj), Value::Object(query_obj)) => self.matches_query(doc_value, query_value),
(Value::Number(doc_num), Value::Number(query_num)) => self.numbers_equal(doc_num, query_num),
_ => doc_value == query_value,
}
}
fn numbers_equal(&self, doc_num: &Number, query_num: &Number) -> bool {
// Try comparing as i64 (signed integers)
if let (Some(doc_i64), Some(query_i64)) = (doc_num.as_i64(), query_num.as_i64()) {
return doc_i64 == query_i64;
}
// Try comparing as u64 (unsigned integers)
if let (Some(doc_u64), Some(query_u64)) = (doc_num.as_u64(), query_num.as_u64()) {
return doc_u64 == query_u64;
}
// Try comparing as f64 (floating point)
if let (Some(doc_f64), Some(query_f64)) = (doc_num.as_f64(), query_num.as_f64()) {
return (doc_f64 - query_f64).abs() < f64::EPSILON;
}
// If none of the above, numbers are not equal
false
}
fn matches_query(&self, doc: &Value, query: &Value) -> bool {
match (doc, query) {
(Value::Object(doc_obj), Value::Object(query_obj)) => {
for (key, query_value) in query_obj {
match doc_obj.get(key) {
Some(doc_value) => {
if !self.value_matches(doc_value, query_value) {
return false;
}
}
None => {
// Key doesn't exist in the document
return false;
}
}
}
true
}
_ => false,
}
}
}
Конечно! Вот C# эквивалент вашего кода:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
public class Document
{
public JToken Content { get; private set; }
public DateTime CreatedAt { get; set; }
public Document(JToken content, DateTime createdAt)
{
this.Content = content;
this.CreatedAt = createdAt;
}
public void SetContent(JToken content)
{
this.Content = content;
}
}
public class Collection
{
public string Name { get; set; }
private Dictionary<string, Document> documents;
// Конструктор
public Collection(string name)
{
this.Name = name;
this.documents = new Dictionary<string, Document>();
}
public IEnumerable<Document> Iter()
{
return documents.Values;
}
public string Add(JToken doc)
{
string index = Guid.NewGuid().ToString(); // Или используйте Nanoid.NET для генерации nanoid
var newDocument = new Document(doc, DateTime.UtcNow);
documents[index] = newDocument;
return index;
}
public Document Get(string index)
{
Document doc;
documents.TryGetValue(index, out doc);
return doc; // Вернёт null, если не найдено
}
public List<Document> GetAllDocuments()
{
return documents.Values.ToList();
}
public IEnumerable<Document> GetAllDocumentsIter()
{
return documents.Values;
}
public Document GetDocumentById(string index)
{
return Get(index);
}
public bool UpdateDocument(string index, JToken doc)
{
Document existing;
if (documents.TryGetValue(index, out existing))
{
existing.SetContent(doc);
return true;
}
else
{
// Документ не найден
return false;
}
}
public Document Remove(string index)
{
Document doc;
if (documents.TryGetValue(index, out doc))
{
documents.Remove(index);
return doc;
}
else
{
// Документ не найден
return null;
}
}
public List<Document> Find(JToken query)
{
return documents.Values
.Where(doc => MatchesQuery(doc.Content, query))
.ToList();
}
private bool ValueMatches(JToken docValue, JToken queryValue)
{
if (docValue.Type == JTokenType.Object && queryValue.Type == JTokenType.Object)
{
return MatchesQuery(docValue, queryValue);
}
else if ((docValue.Type == JTokenType.Integer || docValue.Type == JTokenType.Float) &&
(queryValue.Type == JTokenType.Integer || queryValue.Type == JTokenType.Float))
{
return NumbersEqual(docValue, queryValue);
}
else
{
return JToken.DeepEquals(docValue, queryValue);
}
}
private bool NumbersEqual(JToken docNum, JToken queryNum)
{
if (docNum.Type == JTokenType.Integer && queryNum.Type == JTokenType.Integer)
{
long docInt = docNum.Value<long>();
long queryInt = queryNum.Value<long>();
return docInt == queryInt;
}
else
{
double docDouble = docNum.Value<double>();
double queryDouble = queryNum.Value<double>();
return Math.Abs(docDouble - queryDouble) < 1e-8;
}
}
private bool MatchesQuery(JToken doc, JToken query)
{
if (doc.Type == JTokenType.Object && query.Type == JTokenType.Object)
{
JObject docObj = (JObject)doc;
JObject queryObj = (JObject)query;
foreach (var kvp in queryObj)
{
JToken queryValue = kvp.Value;
JToken docValue;
if (docObj.TryGetValue(kvp.Key, out docValue))
{
if (!ValueMatches(docValue, queryValue))
{
return false;
}
}
else
{
// Ключ не существует в документе
return false;
}
}
return true;
}
return false;
}
}
Объяснение:
Document класс: Реализован для хранения содержимого документа (Content) и времени его создания (CreatedAt). Метод SetContent позволяет обновить содержимое документа.
Collection класс:
Конструктор: Инициализирует коллекцию с заданным именем и пустым словарём документов.
Add: Добавляет новый документ в коллекцию с уникальным идентификатором. Используется Guid.NewGuid().ToString() для генерации уникального ID. Если вы хотите использовать nanoid, вы можете установить пакет Nanoid.NET и заменить генерацию ID.
Get/GetDocumentById: Возвращает документ по идентификатору или null, если документ не найден.
GetAllDocuments/GetAllDocumentsIter/Iter: Возвращает все документы в коллекции.
UpdateDocument: Обновляет содержимое существующего документа. Возвращает true, если обновление успешно, или false, если документ не найден.
Remove: Удаляет документ из коллекции и возвращает его. Возвращает null, если документ не найден.
Find: Находит и возвращает список документов, соответствующих запросу query. Используются вспомогательные методы MatchesQuery, ValueMatches и NumbersEqual для сравнения содержимого документов с запросом.
ValueMatches, NumbersEqual, MatchesQuery: Вспомогательные методы для сравнения значений в документах с запросом, учитывая различия в типах данных и особенности сравнения чисел.
Зависимости:
Newtonsoft.Json.Linq: Используется для работы с JSON-подобными структурами данных (JToken, JObject и т.д.). Убедитесь, что вы установили пакет Newtonsoft.Json через NuGet.Примечания:
Обработка ошибок в данном коде осуществляется через возвращение null или false, если документ не найден. Вы можете изменить это поведение, выбрасывая исключения или используя более продвинутые методы обработки ошибок, если это необходимо.
Для точного сравнения чисел с плавающей точкой используется небольшой эпсилон (1e-8). При необходимости вы можете настроить точность сравнения.
Если у вас есть вопросы или требуется дополнительная помощь, дайте знать!
Not yet included in a published release.