xxxxxxxxxx
public class YourDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new { sc.StudentId, sc.CourseId });
modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.StudentId);
modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Course)
.WithMany(c => c.StudentCourses)
.HasForeignKey(sc => sc.CourseId);
}
}
xxxxxxxxxx
using System;
public class PrimeChecker
{
public static bool IsPrime(int number)
{
if (number <= 1)
{
return false;
}
else if (number <= 3)
{
return true;
}
else if (number % 2 == 0 || number % 3 == 0)
{
return false;
}
int i = 5;
while (i * i <= number)
{
if (number % i == 0 || number % (i + 2) == 0)
{
return false;
}
i += 6;
}
return true;
}
public static void Main(string[] args)
{
int num = 17;
if (IsPrime(num))
{
Console.WriteLine(num + " is a prime number.");
}
else
{
Console.WriteLine(num + " is not a prime number.");
}
}
}
xxxxxxxxxx
using System;
class Program
{
// Method with optional arguments
static void DisplayInfo(string name, int age = 25, string city = "Unknown")
{
Console.WriteLine($"Name: {name}, Age: {age}, City: {city}");
}
static void Main()
{
// Calling the method with different combinations of arguments
DisplayInfo("John"); // Uses default values for age and city
DisplayInfo("Alice", 30); // Overrides age, uses default value for city
DisplayInfo("Bob", 28, "New York"); // Overrides both age and city
Console.ReadLine();
}
}
xxxxxxxxxx
using System.Collections.Concurrent;
using System.Collections.Generic;
// ...
// Original code with Dictionary and List
Dictionary<string, List<ClientAccesToken>> _tokenCollection = new Dictionary<string, List<ClientAccesToken>>();
// Convert to ConcurrentDictionary and ConcurrentBag
ConcurrentDictionary<string, ConcurrentBag<ClientAccesToken>> _concurrentTokenCollection = new ConcurrentDictionary<string, ConcurrentBag<ClientAccesToken>>();
// Example usage:
string key = "exampleKey";
ClientAccesToken token = new ClientAccesToken(); // Assuming ClientAccesToken is a class in your code
// Using original Dictionary and List
if (!_tokenCollection.ContainsKey(key))
{
_tokenCollection[key] = new List<ClientAccesToken>();
}
_tokenCollection[key].Add(token);
// Using ConcurrentDictionary and ConcurrentBag
_concurrentTokenCollection.AddOrUpdate(
key,
new ConcurrentBag<ClientAccesToken>(new List<ClientAccesToken> { token }),
(_, bag) =>
{
bag.Add(token);
return bag;
}
);
xxxxxxxxxx
string formattedString = string.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek);
Console.WriteLine(formattedString);
xxxxxxxxxx
using System;
using System.Collections.Generic;
using UnityEngine;
public class JsonStackExample : MonoBehaviour
{
private Stack<string> jsonStack = new Stack<string>();
void Start()
{
// 添加JSON字符串到Stack中
AddJsonToStack("{\"name\": \"John\", \"age\": 30}");
AddJsonToStack("{\"name\": \"Alice\", \"age\": 25}");
AddJsonToStack("{\"name\": \"Bob\", \"age\": 40}");
// 从Stack中读取并输出JSON字符串
ReadJsonFromStack();
}
void AddJsonToStack(string json)
{
jsonStack.Push(json);
}
void ReadJsonFromStack()
{
while (jsonStack.Count > 0)
{
string json = jsonStack.Pop();
Debug.Log("JSON from Stack: " + json);
// 在这里你可以对JSON进行解析或其他操作
// 例如,你可以使用JsonUtility.FromJson<T>()方法将JSON字符串转换为对象
// 详细操作取决于你想要做的处理
}
}
}
xxxxxxxxxx
[CommandMethod("Convert3DTo2D")]
public static void Convert3DTo2D()
{
// Get the current document and database
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// Start a transaction
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// Prompt the user to select the 3D objects to convert
PromptSelectionResult selectionResult = doc.Editor.GetSelection();
if (selectionResult.Status != PromptStatus.OK)
{
ed.WriteMessage("\nNo objects selected.");
return;
}
// Get the selected objects
SelectionSet selectionSet = selectionResult.Value;
using (Transaction transaction = db.TransactionManager.StartTransaction())
{
foreach (SelectedObject obj in selectionSet)
{
if (obj.ObjectId.ObjectClass.DxfName.Contains("POLYLINE"))
{
Polyline pline = transaction.GetObject(obj.ObjectId, OpenMode.ForWrite) as Polyline;
if (pline != null)
{
// Set the elevation of each vertex to zero
for (int i = 0; i < pline.NumberOfVertices; i++)
{
Point3d vertex3D = pline.GetPoint3dAt(i);
vertex3D = new Point3d(vertex3D.X, vertex3D.Y, 0.0);
pline.SetPointAt(i, vertex3D);
}
// Optionally, close the polyline if it's not closed
if (!pline.Closed)
{
pline.Closed = true;
}
}
}
}
// Commit the transaction
transaction.Commit();
}
}
}
xxxxxxxxxx
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Assuming you have dictionaries dic1 and dic2
Dictionary<string, object> dic1 = new Dictionary<string, object>();
Dictionary<string, object> dic2 = new Dictionary<string, object>();
// Populate dictionaries with sample data (replace this with your actual data)
dic1["key1"] = "value1";
dic1["key2"] = 123;
dic1["key3"] = true;
dic2["key1"] = "value1";
dic2["key2"] = 123;
// Perform the comparison
bool areEqual = CompareDictionaries(dic1, dic2);
// Output the result
Console.WriteLine($"Are the dictionaries equal? {areEqual}");
}
static bool CompareDictionaries(Dictionary<string, object> dic1, Dictionary<string, object> dic2)
{
// Iterate through the keys in dic2
foreach (var key in dic2.Keys)
{
// Check if the key is present in dic1
if (dic1.TryGetValue(key, out var value1))
{
// Compare the values for the corresponding keys
var value2 = dic2[key];
// Adjust the comparison based on your data types and equality criteria
if (!value1.Equals(value2))
{
// If values don't match, dictionaries are not equal
return false;
}
}
else
{
// If key is not present in dic1, dictionaries are not equal
return false;
}
}
// If all keys and corresponding values match, dictionaries are equal
return true;
}
}
xxxxxxxxxx
public async Task<Status> LockAccountAsync(string username)
{
var status = new Status();
var user = await _userManager.FindByNameAsync(username);
if (user != null)
{
// Lock the account for 1 minute
user.LockoutEnd = DateTime.Now.AddMinutes(1);
await _userManager.UpdateAsync(user);
// Schedule a background task to unlock the account after 1 minute
ScheduleUnlockTask(user.Id, DateTime.Now.AddMinutes(1));
status.StatusCode = 1;
status.Message = "Account locked successfully";
}
else
{
status.StatusCode = 0;
status.Message = "No user found";
}
return status;
}
private async void ScheduleUnlockTask(string userId, DateTime unlockTime)
{
// Assume you have some background task scheduler or queue mechanism
// Here, you can use a timer, Hangfire, or any other scheduling mechanism
// Example using Timer
var timer = new Timer(async (_) =>
{
var user = await _userManager.FindByIdAsync(userId);
if (user != null && user.LockoutEnd >= DateTime.Now)
{
// Unlock the account
user.LockoutEnd = null;
await _userManager.UpdateAsync(user);
}
timer.Dispose(); // Dispose the timer after execution
}, null, unlockTime - DateTime.Now, TimeSpan.Zero);
}