Bỏ qua để đến nội dung

Snippets thường dùng

Snippets dùng để copy nhanh và chỉnh theo nhu cầu. Ưu tiên mẫu ngắn, dễ hiểu, không phụ thuộc quá nhiều framework.

Console.Write("Nhập tên: ");
string? name = Console.ReadLine();
Console.WriteLine($"Xin chào {name}");
Console.Write("Nhập tuổi: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age))
{
Console.WriteLine($"Tuổi: {age}");
}
else
{
Console.WriteLine("Tuổi không hợp lệ");
}
var names = new List<string> { "An", "Binh", "Chi" };
foreach (string name in names)
{
Console.WriteLine(name);
}
var scores = new Dictionary<string, int>
{
["An"] = 9,
["Binh"] = 8
};
foreach (var pair in scores)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
var numbers = new List<int> { 5, 1, 3 };
numbers.Sort();
var users = new List<User>
{
new("An", 20),
new("Binh", 18)
};
var sortedUsers = users.OrderBy(u => u.Age).ToList();
public record User(string Name, int Age);
var products = new List<Product>
{
new("Mouse", 150000, "Tech"),
new("Book", 90000, "Education")
};
var techProducts = products
.Where(p => p.Category == "Tech")
.ToList();
public record Product(string Name, decimal Price, string Category);
var groups = products.GroupBy(p => p.Category);
foreach (var group in groups)
{
Console.WriteLine(group.Key);
foreach (var product in group)
{
Console.WriteLine(product.Name);
}
}
try
{
RunJob();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
using System.Text.Json;
var settings = new AppSettings("Dark", true);
string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText("settings.json", json);
string saved = File.ReadAllText("settings.json");
AppSettings? loaded = JsonSerializer.Deserialize<AppSettings>(saved);
public record AppSettings(string Theme, bool EnableSearch);
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var todos = new List<Todo>();
app.MapGet("/todos", () => todos);
app.MapPost("/todos", (Todo todo) =>
{
todos.Add(todo);
return Results.Created($"/todos/{todo.Id}", todo);
});
app.Run();
public record Todo(int Id, string Title, bool Done);
app.MapPost("/products", (CreateProductRequest request) =>
{
if (string.IsNullOrWhiteSpace(request.Name))
{
return Results.BadRequest("Name is required");
}
return Results.Created("/products/1", request);
});
public record CreateProductRequest(string Name, decimal Price);
using var client = new HttpClient();
string json = await client.GetStringAsync("https://example.com/api/products");
Console.WriteLine(json);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
string json = await client.GetStringAsync("https://example.com", cts.Token);
var products = await db.Products
.AsNoTracking()
.Where(p => p.Price > 100000)
.OrderBy(p => p.Name)
.Select(p => new ProductDto(p.Id, p.Name))
.ToListAsync();
public record ProductDto(int Id, string Name);
void CreateUser(string email)
{
if (string.IsNullOrWhiteSpace(email))
{
throw new ArgumentException("Email is required", nameof(email));
}
Console.WriteLine(email);
}
using UnityEngine;
public class Move2D : MonoBehaviour
{
[SerializeField] private float speed = 5f;
void Update()
{
Vector2 input = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
transform.Translate(input.normalized * speed * Time.deltaTime);
}
}
using UnityEngine;
public class Move3D : MonoBehaviour
{
[SerializeField] private float speed = 5f;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 move = new(h, 0f, v).normalized;
transform.Translate(move * speed * Time.deltaTime);
}
}
Nhu cầuSnippet
Nhập consoleConsole.ReadLine
Parse sốint.TryParse
Duyệt listforeach
Lọc dataWhere
Gom nhómGroupBy
JSONJsonSerializer
API nhỏMinimal API
Unity movementUpdate + Time.deltaTime
HTTP APIHttpClient + await
Database read-onlyAsNoTracking + projection
Validate nhanhGuard clause
  • Copy snippet nhưng quên thêm using.
  • Dùng snippet demo cho production mà chưa thêm validation/logging.
  • Trong Unity, quên nhân Time.deltaTime.
  • Dùng snippet EF Core mà thiếu package/namespace Microsoft.EntityFrameworkCore.
  • Dùng HttpClient trong loop bằng cách tạo quá nhiều instance.

snippet, code mẫu, đọc input, parse int, duyệt List, duyệt Dictionary, Sort List, filter List, GroupBy, try catch, read write JSON, Minimal API, HttpClient, CancellationToken, EF Core, AsNoTracking, guard clause, Unity movement 2D, Unity movement 3D, di chuyển nhân vật