Here are the examples of the csharp api System.Console.WriteLine(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
200 Examples
19
Source : SystemConsole.cs
with MIT License
from lechu445
with MIT License
from lechu445
public void WriteLine(bool value)
=> Console.WriteLine(value);
19
Source : MVCTests.cs
with MIT License
from loic-lopez
with MIT License
from loic-lopez
[Test]
public void TestEvents()
{
TestModel testModel = new TestModel();
testModel.Initialize();
int value = new Random().Next();
const string fieldName = "Value";
void OnFieldWillUpdate(object model, object newValue, object oldValue, PropertyChangedEventArgs eventArgs)
{
replacedert.True((int)oldValue == ((TestModel)model).Value);
replacedert.True(eventArgs.PropertyName == fieldName);
replacedert.True(newValue != oldValue);
replacedert.True((int)newValue == value);
_onFieldWillUpdateRunned = true;
}
void OnFieldDidUpdate(object model, object newValue, PropertyChangedEventArgs eventArgs)
{
replacedert.True(eventArgs.PropertyName == fieldName);
replacedert.True(value == (int) newValue);
_onFieldDidUpdateRunned = true;
}
testModel.OnFieldWillUpdate += OnFieldWillUpdate;
testModel.OnFieldDidUpdate += OnFieldDidUpdate;
// Call setter and check if the events are fired
testModel.Value = value;
replacedert.True(testModel.Value == value);
replacedert.IsTrue(_onFieldWillUpdateRunned);
replacedert.IsTrue(_onFieldDidUpdateRunned);
// disable OnFieldWillUpdate event and check not runned
_onFieldWillUpdateRunned = false;
_onFieldDidUpdateRunned = false;
value = 42;
testModel.isOnFieldWillUpdateEnabled = false;
testModel.Value = value;
replacedert.True(testModel.Value == value);
Console.WriteLine(_onFieldDidUpdateRunned);
replacedert.IsFalse(_onFieldWillUpdateRunned);
replacedert.IsTrue(_onFieldDidUpdateRunned);
// disable OnFieldDidUpdate event and check not runned
_onFieldWillUpdateRunned = false;
_onFieldDidUpdateRunned = false;
value++;
testModel.isOnFieldWillUpdateEnabled = true;
testModel.isOnFieldDidUpdateEnabled = false;
testModel.Value = value;
replacedert.True(testModel.Value == value);
Console.WriteLine(_onFieldDidUpdateRunned);
replacedert.IsTrue(_onFieldWillUpdateRunned);
replacedert.IsFalse(_onFieldDidUpdateRunned);
// disable all events and check not runned
_onFieldWillUpdateRunned = false;
_onFieldDidUpdateRunned = false;
value++;
testModel.isOnFieldWillUpdateEnabled = false;
testModel.isOnFieldDidUpdateEnabled = false;
testModel.Value = value;
replacedert.True(testModel.Value == value);
Console.WriteLine(_onFieldDidUpdateRunned);
replacedert.IsFalse(_onFieldWillUpdateRunned);
replacedert.IsFalse(_onFieldDidUpdateRunned);
// remove events
testModel.OnFieldWillUpdate -= OnFieldWillUpdate;
testModel.OnFieldDidUpdate -= OnFieldDidUpdate;
}
19
Source : Palindrome.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
WriteLine(checkPalindrome("ana"));
WriteLine(checkPalindrome("abba"));
WriteLine(checkPalindrome("oki"));
}
19
Source : InstanceProblem.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() => WriteLine(new Animal().estaVivo);
19
Source : OverloadResolution.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var x = new MyList<int>();
var y = x;
WriteLine(x.Equals(y));
}
19
Source : GetField.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var bloco1 = new Block<string>("título", "conteúdo");
var bloco2 = new Block<string>("título2", "conteúdo2");
WriteLine(bloco1.Equals(bloco2));
WriteLine(bloco1.Equals(bloco1));
}
19
Source : Posisitve.cs
with MIT License
from maniero
with MIT License
from maniero
static void Main() {
Write("Digite um número: ");
if (!int.TryParse(ReadLine(), out var numero)) return;
WriteLine(ÉPositivo(numero));
}
19
Source : ConstructorParameter.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var lista = CriarLista();
var teste = new teste(lista);
lista[0] = "Example";
WriteLine(teste.testeVeridico());
teste.OutroTeste(lista);
WriteLine(teste.testeVeridico());
}
19
Source : And.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var x = 1;
var y = 2;
var a = x & y;
var b = x == 1;
var c = y == 2;
var d = x & y;
var e = (x & y) == 0;
WriteLine(a);
WriteLine(d); //note que é um inteiro
WriteLine(e);
//if (x & y) WriteLine("ok"); //não funciona porque if espera um bool e o resultado é int
if (b & c) WriteLine("ok"); else WriteLine(" não ok");
if (Teste(x) & Teste(y)) WriteLine("& - ok"); else WriteLine("&");
if (Teste(x) && Teste(y)) WriteLine("&& - ok"); else WriteLine("&&");
if (Teste(x) | Teste(y)) WriteLine("| - ok"); else WriteLine("|");
if (Teste(x) || Teste(y)) WriteLine("|| - ok"); else WriteLine("||");
if (Teste(y) & Teste(x)) WriteLine("& - ok"); else WriteLine("&");
if (Teste(y) && Teste(x)) WriteLine("&& - ok"); else WriteLine("&&");
if (Teste(y) | Teste(x)) WriteLine("| - ok"); else WriteLine("|");
if (Teste(y) || Teste(x)) WriteLine("|| - ok"); else WriteLine("||");
}
19
Source : AndBigInteger.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
WriteLine(VerificaPermissao((BigInteger)1, (BigInteger)0));
WriteLine(VerificaPermissao((BigInteger)1, (BigInteger)1));
WriteLine(VerificaPermissao((BigInteger)2, (BigInteger)1));
}
19
Source : Equals.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
// cria duas variáveis iguais mas distintas uma da outra
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
WriteLine (a == b);
WriteLine (a.Equals(b));
// o mesmo teste usando os mesmo dados mas como variáveis do tipo `Object`
object c = a;
object d = b;
WriteLine (c == d);
WriteLine (c.Equals(d));
WriteLine("-----------------");
int myInt = 1;
short myShort = 1;
object objInt1 = myInt;
object objInt2 = myInt;
object objShort = myShort;
WriteLine(myInt == myShort); // cenário 1 true
WriteLine(myShort == myInt); // cenário 2 true
WriteLine(myInt.Equals(myShort)); // cenário 3 true
WriteLine(myShort.Equals(myInt)); // cenário 4 false!
WriteLine(objInt1 == objInt1); // cenário 5 true
WriteLine(objInt1 == objShort); // cenário 6 false!!
WriteLine(objInt1 == objInt2); // cenário 7 false!!!
WriteLine(Equals(objInt1, objInt2)); // cenário 8 true
WriteLine(Equals(objInt1, objShort)); // cenário 9 false!?!
WriteLine("-----------------");
string s1 = "abc";
string s2 = "abc";
WriteLine(object.ReferenceEquals(s1, s2)); //retorna true
string s3 = "abc";
string s4t = "ab";
string s4 = s4t + "c";
WriteLine(object.ReferenceEquals(s3, s4)); //retorna false
WriteLine(s3 == s4); //retorna true
}
19
Source : Precedence.cs
with MIT License
from maniero
with MIT License
from maniero
public static int Main() {
var conta = new Conta();
var txtValor = new Form();
bool retorno;
if ((retorno = conta.Saca(Convert.ToDouble(txtValor.Text)))) {
Console.WriteLine(retorno);
return 1;
}
return 0;
}
19
Source : Relational.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var x = 1;
WriteLine(x == 1 || x == 2);
WriteLine(x == 1 || x != 2);
WriteLine(x != 1 || x != 2);
WriteLine(x == 1 && x == 2);
WriteLine(x == 1 && x != 2);
WriteLine(x != 1 && x != 2);
WriteLine(x == 3 || x == 2);
WriteLine(x == 3 || x != 2);
WriteLine(x != 3 || x != 1);
WriteLine(x == 3 && x == 2);
WriteLine(x == 3 && x != 2);
WriteLine(x != 3 && x != 2);
}
19
Source : PropertyMemory.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var objeto = new Clreplacede(1);
WriteLine(objeto.IsFree);
}
19
Source : CompareChar.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
WriteLine(eNumero(""));
WriteLine(eNumero("a"));
WriteLine(eNumero("5"));
}
19
Source : Comparing.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
WriteLine(Teste("João", "048", "abc"));
WriteLine(Teste("João", "048", "abc", ""));
WriteLine(Teste("", "João", "048", "abc"));
WriteLine(Teste("", null));
WriteLine(Teste2("", null));
WriteLine(Teste2("", null, "João", "048", "abc"));
}
19
Source : ContainsCaseAndAccentInsensitive.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var mainStr = "José João";
Console.WriteLine(mainStr.ContainsInsensitive("JOA"));
Console.WriteLine(mainStr.ContainsInsensitive("jose"));
Console.WriteLine(mainStr.ContainsInsensitive("josé"));
}
19
Source : ContainsCaseInsensitive.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
var mainStr = "Joaquim Pedro Soares";
Console.WriteLine(mainStr.Contains("JOA", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(mainStr.Contains("Quim", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(mainStr.Contains("PEDRO", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(mainStr.Contains("PeDro", StringComparison.OrdinalIgnoreCase));
}
19
Source : NullWhiteSpace.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
string nullString = null;
string emptyString = "";
string spaceString = " ";
string tabString = "\t";
string newlineString = "\n";
string nonEmptyString = "texto";
WriteLine(string.IsNullOrEmpty(nullString));
WriteLine(string.IsNullOrEmpty(emptyString));
WriteLine(string.IsNullOrEmpty(spaceString));
WriteLine(string.IsNullOrEmpty(tabString));
WriteLine(string.IsNullOrEmpty(newlineString));
WriteLine(string.IsNullOrEmpty(nonEmptyString));
WriteLine();
WriteLine(string.IsNullOrWhiteSpace(nullString));
WriteLine(string.IsNullOrWhiteSpace(emptyString));
WriteLine(string.IsNullOrWhiteSpace(spaceString));
WriteLine(string.IsNullOrWhiteSpace(tabString));
WriteLine(string.IsNullOrWhiteSpace(newlineString));
WriteLine(string.IsNullOrWhiteSpace(nonEmptyString));
}
19
Source : Palindrome.cs
with MIT License
from maniero
with MIT License
from maniero
public static void Main() {
WriteLine(EhPalindromo("4004"));
WriteLine(EhPalindromo("4002"));
}
19
Source : Engine.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
public void InterpretCommand(string line)
{
string[] split = line.Split();
string cmd = split[0];
if (cmd == "Add")
{
customList.Add(split[1]);
}
else if (cmd == "Remove")
{
customList.Remove(int.Parse(split[1]));
}
else if (cmd == "Contains")
{
Console.WriteLine(customList.Contains(split[1]));
}
else if (cmd == "Swap")
{
customList.Swap(int.Parse(split[1]), int.Parse(split[2]));
}
else if (cmd == "Greater")
{
Console.WriteLine(customList.CountGreaterThen(split[1]));
}
else if (cmd == "Max")
{
Console.WriteLine(customList.Max());
}
else if (cmd == "Min")
{
Console.WriteLine(customList.Min());
}
else if (cmd == "Print")
{
foreach (var str in customList)
{
Console.WriteLine(str);
}
}
else if (cmd == "Sort")
{
Sorter.Sort(customList);
}
}
19
Source : Engine.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
public void InterpretCommand(string line)
{
string[] split = line.Split();
string cmd = split[0];
if (cmd == "Add")
{
customList.Add(split[1]);
}
else if (cmd == "Remove")
{
customList.Remove(int.Parse(split[1]));
}
else if (cmd == "Contains")
{
Console.WriteLine(customList.Contains(split[1]));
}
else if (cmd == "Swap")
{
customList.Swap(int.Parse(split[1]), int.Parse(split[2]));
}
else if (cmd == "Greater")
{
Console.WriteLine(customList.CountGreaterThen(split[1]));
}
else if (cmd == "Max")
{
Console.WriteLine(customList.Max());
}
else if (cmd == "Min")
{
Console.WriteLine(customList.Min());
}
else if (cmd == "Print")
{
foreach (var str in customList)
{
Console.WriteLine(str);
}
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
static void Main(string[] args)
{
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
Console.WriteLine(Math.Abs(a - b) < 0.000001);
}
19
Source : Program.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
public static void Main()
{
Console.WriteLine(IsPrime(long.Parse(Console.ReadLine())));
}
19
Source : LuisRecognizerTests.cs
with MIT License
from microsoft
with MIT License
from microsoft
[Theory]
[InlineData(false, null, null, null, null, null)]
[InlineData(null, 55, null, null, null, null)]
[InlineData(null, null, false, null, null, null)]
[InlineData(null, null, null, "Override-EC0A-472D-95B7-A7132D159E03", null, null)]
[InlineData(null, null, null, null, true, null)]
[InlineData(null, null, null, null, null, false)]
[InlineData(null, null, null, null, null, null)]
public async Task ShouldOverrideRecognizerOptionsIfProvided(bool? includeAllIntents, double? timezoneOffset, bool? spellCheck, string bingSpellCheckSubscriptionKey, bool? log, bool? staging)
{
// Arrange
// Initialize options with non default values so we can replacedert they have been overriden.
var constructorOptions = new LuisPredictionOptions()
{
IncludeAllIntents = true,
TimezoneOffset = 42,
SpellCheck = true,
BingSpellCheckSubscriptionKey = "Fake2806-EC0A-472D-95B7-A7132D159E03",
Log = false,
Staging = true,
};
// Create overriden options for call
var overridenOptions = new LuisRecognizerOptionsV2(_luisApp)
{
PredictionOptions = new LuisPredictionOptions()
{
IncludeAllIntents = includeAllIntents,
TimezoneOffset = timezoneOffset,
SpellCheck = spellCheck,
BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey,
Log = log,
Staging = staging
}
};
// Create combined options for replacedertion taking the test case value if not null or the constructor value if not null.
var expectedOptions = new LuisPredictionOptions()
{
IncludeAllIntents = includeAllIntents,
TimezoneOffset = timezoneOffset,
SpellCheck = spellCheck,
BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey,
Log = log ?? true,
Staging = staging,
};
#pragma warning disable CS0618 // Type or member is obsolete
var opts = new LuisRecognizerOptionsV2(_luisApp)
{
PredictionOptions = constructorOptions,
TelemetryClient = constructorOptions.TelemetryClient,
};
// var sut = new LuisRecognizer(_luisApp, constructorOptions, clientHandler: _mockHttpClientHandler);
var sut = new LuisRecognizer(opts, clientHandler: _mockHttpClientHandler);
// Act/replacedert RecognizeAsync override
await sut.RecognizeAsync(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None);
replacedertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions);
#pragma warning disable CS0618 // Type or member is obsolete
// these values can't be overriden and should stay unchanged.
Console.WriteLine(constructorOptions.TelemetryClient == sut.TelemetryClient);
replacedert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient);
replacedert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation);
// Act/replacedert RecognizeAsync<T> override
await sut.RecognizeAsync<Contoso_App>(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None);
replacedertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions);
// these values can't be overriden and should stay unchanged.
replacedert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient);
replacedert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation);
}
19
Source : LuisRecognizerTests.cs
with MIT License
from microsoft
with MIT License
from microsoft
[Theory]
[InlineData(false, null, null, null, null, null)]
[InlineData(null, 55, null, null, null, null)]
[InlineData(null, null, false, null, null, null)]
[InlineData(null, null, null, "Override-EC0A-472D-95B7-A7132D159E03", null, null)]
[InlineData(null, null, null, null, true, null)]
[InlineData(null, null, null, null, null, false)]
[InlineData(null, null, null, null, null, null)]
public async Task ShouldOverridePredictionOptionsIfProvided(bool? includeAllIntents, double? timezoneOffset, bool? spellCheck, string bingSpellCheckSubscriptionKey, bool? log, bool? staging)
{
// Arrange
// Initialize options with non default values so we can replacedert they have been overriden.
var constructorOptions = new LuisPredictionOptions()
{
IncludeAllIntents = true,
TimezoneOffset = 42,
SpellCheck = true,
BingSpellCheckSubscriptionKey = "Fake2806-EC0A-472D-95B7-A7132D159E03",
Log = false,
Staging = true,
};
// Create overriden options for call
var overridenOptions = new LuisPredictionOptions()
{
IncludeAllIntents = includeAllIntents,
TimezoneOffset = timezoneOffset,
SpellCheck = spellCheck,
BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey,
Log = log,
Staging = staging,
};
#pragma warning disable CS0618 // Type or member is obsolete
// Create combined options for replacedertion taking the test case value if not null or the constructor value if not null.
var expectedOptions = new LuisPredictionOptions()
{
IncludeAllIntents = includeAllIntents ?? constructorOptions.IncludeAllIntents,
TimezoneOffset = timezoneOffset ?? constructorOptions.TimezoneOffset,
SpellCheck = spellCheck ?? constructorOptions.SpellCheck,
BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey ?? constructorOptions.BingSpellCheckSubscriptionKey,
Log = log ?? constructorOptions.Log,
Staging = staging ?? constructorOptions.Staging,
LogPersonalInformation = constructorOptions.LogPersonalInformation,
};
var opts = new LuisRecognizerOptionsV2(_luisApp)
{
PredictionOptions = constructorOptions,
TelemetryClient = constructorOptions.TelemetryClient,
};
// var sut = new LuisRecognizer(_luisApp, constructorOptions, clientHandler: _mockHttpClientHandler);
var sut = new LuisRecognizer(opts, clientHandler: _mockHttpClientHandler);
// Act/replacedert RecognizeAsync override
await sut.RecognizeAsync(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None);
replacedertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions);
// these values can't be overriden and should stay unchanged.
Console.WriteLine(constructorOptions.TelemetryClient == sut.TelemetryClient);
replacedert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient);
replacedert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation);
// Act/replacedert RecognizeAsync<T> override
await sut.RecognizeAsync<Contoso_App>(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None);
replacedertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions);
// these values can't be overriden and should stay unchanged.
replacedert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient);
replacedert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation);
#pragma warning restore CS0618 // Type or member is obsolete
}
19
Source : LogicDefine.cs
with GNU General Public License v3.0
from minishmaker
with GNU General Public License v3.0
from minishmaker
public bool CanReplace(string input)
{
Console.WriteLine(Expression != null);
return Expression != null && Expression.IsMatch(input);
}
19
Source : Program.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
static void Test1()
{
var services = new ServiceCollection();
services.AddRedis("test1", "server=centos.newlifex.com:6000;preplacedword=Preplaced@word;db=9");
services.AddRedis("test2", "server=centos.newlifex.com:6000;preplacedword=Preplaced@word;db=9");
var provider = services.BuildServiceProvider();
//var ic = provider.GetRequiredService<Redis>();
var ic = provider.GetServices<Redis>().FirstOrDefault(e => e.Name == "test1");
//var ic = new FullRedis("127.0.0.1:6379", null, 3);
//var ic = new FullRedis();
//ic.Server = "127.0.0.1:6379";
//ic.Db = 3;
ic.Log = XTrace.Log;
// 简单操作
Console.WriteLine("共有缓存对象 {0} 个", ic.Count);
ic.Set("name", "大石头");
Console.WriteLine(ic.Get<String>("name"));
var ks = ic.Execute(null, c => c.Execute<String[]>("KEYS", "*"));
var keys = ic.Keys;
ic.Set("time", DateTime.Now, 1);
Console.WriteLine(ic.Get<DateTime>("time").ToFullString());
Thread.Sleep(1100);
Console.WriteLine(ic.Get<DateTime>("time").ToFullString());
// 列表
var list = ic.GetList<DateTime>("list");
list.Add(DateTime.Now);
list.Add(DateTime.Now.Date);
list.RemoveAt(1);
Console.WriteLine(list[list.Count - 1].ToFullString());
// 字典
var dic = ic.GetDictionary<DateTime>("dic");
dic.Add("xxx", DateTime.Now);
Console.WriteLine(dic["xxx"].ToFullString());
// 队列
var mq = ic.GetQueue<String>("queue");
mq.Add(new[] { "abc", "g", "e", "m" });
var arr = mq.Take(3);
Console.WriteLine(arr.Join(","));
// 集合
var set = ic.GetSet<String>("181110_1234");
set.Add("xx1");
set.Add("xx2");
set.Add("xx3");
Console.WriteLine(set.Count);
Console.WriteLine(set.Contains("xx2"));
Console.WriteLine("共有缓存对象 {0} 个", ic.Count);
}
19
Source : Program.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
static void Test3()
{
var dic = new SortedList<String, String>(StringComparer.Ordinal)
{
["subscription"] = "aaa",
["subVersion"] = "ccc",
};
Console.WriteLine(dic.Join(",", e => $"{e.Key}={e.Value}"));
Console.WriteLine('s' > 'V');
Console.WriteLine();
var cmp = Comparer<String>.Default;
Console.WriteLine(cmp.Compare("s", "S"));
Console.WriteLine(cmp.Compare("s", "v"));
Console.WriteLine(cmp.Compare("s", "V"));
Console.WriteLine();
var cmp2 = StringComparer.OrdinalIgnoreCase;
Console.WriteLine(cmp2.Compare("s", "S"));
Console.WriteLine(cmp2.Compare("s", "v"));
Console.WriteLine(cmp2.Compare("s", "V"));
Console.WriteLine();
cmp2 = StringComparer.Ordinal;
Console.WriteLine(cmp2.Compare("s", "S"));
Console.WriteLine(cmp2.Compare("s", "v"));
Console.WriteLine(cmp2.Compare("s", "V"));
//dic.Clear();
//dic = dic.OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value);
//Console.WriteLine(dic.Join(",", e => $"{e.Key}={e.Value}"));
var list = new List<BrokerInfo>
{
new BrokerInfo { Name = "A", WriteQueueNums = 5 },
new BrokerInfo { Name = "B", WriteQueueNums = 7,Addresses=new[]{ "111","222"} },
new BrokerInfo { Name = "C", WriteQueueNums = 9 },
};
var list2 = new List<BrokerInfo>
{
new BrokerInfo { Name = "A", WriteQueueNums = 5 },
new BrokerInfo { Name = "B", WriteQueueNums = 7 ,Addresses=new[]{ "111","222"}},
new BrokerInfo { Name = "C", WriteQueueNums = 9 },
};
Console.WriteLine(list[1].Equals(list2[1]));
Console.WriteLine(list2.SequenceEqual(list));
var robin = new WeightRoundRobin();
robin.Set(list.Select(e => e.WriteQueueNums).ToArray());
var count = list.Sum(e => e.WriteQueueNums);
for (var i = 0; i < count; i++)
{
var idx = robin.Get(out var times);
var bk = list[idx];
Console.WriteLine("{0} {1} {2}", i, bk.Name, times - 1);
}
}
19
Source : Program.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
static void Test4()
{
var a1 = File.ReadAllBytes("a1".GetFullPath());
var a2 = File.ReadAllBytes("a2".GetFullPath());
//var ms = new MemoryStream(a1);
//ms.Position += 2;
//var ds = new DeflateStream(ms, CompressionMode.Decompress);
//var buf = ds.ReadBytes();
var buf = a1.ReadBytes(2).Decompress();
var rs = a2.ToBase64() == buf.ToBase64();
Console.WriteLine(rs);
Console.WriteLine(buf.ToStr());
}
19
Source : Program.cs
with MIT License
from niuniuzhu
with MIT License
from niuniuzhu
private static async void TestRedis()
{
Connect();
IDatabase db = redis.GetDatabase();
var person = new Person
{
Id = 12345,
Name = "Fred",
Address = new Address
{
Line1 = "Flat 1",
Line2 = "The Meadows"
},
Addresses = new Dictionary<int, Address>
{
{
0, new Address
{
Line1 = "Flat 2",
Line2 = "The Meadows"
}
},
{
1, new Address
{
Line1 = "Flat 3",
Line2 = "The Meadows"
}
}
},
eTest = ETest.T2
};
MemoryStream ms = new MemoryStream();
Serializer.Serialize( ms, person );
bool t = await db.StringSetAsync( "xx", ms.ToArray() );
Console.WriteLine( t );
ms.Close();
ms.Dispose();
byte[] data = db.StringGet( "xx" );
ms = new MemoryStream( data );
person = Serializer.Deserialize<Person>( ms );
Console.WriteLine( person );
}
19
Source : DotNet45Tests.cs
with GNU Lesser General Public License v3.0
from ntminer
with GNU Lesser General Public License v3.0
from ntminer
[TestMethod]
public void DelegateTest2() {
Func<bool> fun = () => {
Thread.Sleep(1000);
return true;
};
fun.BeginInvoke(ar => {
var f = ar.AsyncState as Func<bool>;
var r = f.EndInvoke(ar);
Console.WriteLine(r);
}, null).AsyncWaitHandle.WaitOne();
}
19
Source : Clone.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
[Test]
public void Example()
{
#region Usage
JObject o1 = new JObject
{
{ "String", "A string!" },
{ "Items", new JArray(1, 2) }
};
Console.WriteLine(o1.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
JObject o2 = (JObject)o1.DeepClone();
Console.WriteLine(o2.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(Object.ReferenceEquals(o1, o2));
// false
#endregion
replacedert.IsTrue(JToken.DeepEquals(o1, o2));
replacedert.IsFalse(Object.ReferenceEquals(o1, o2));
}
19
Source : ToObjectGeneric.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
[Test]
public void Example()
{
#region Usage
JValue v1 = new JValue(true);
bool b = v1.ToObject<bool>();
Console.WriteLine(b);
// true
int i = v1.ToObject<int>();
Console.WriteLine(i);
// 1
string s = v1.ToObject<string>();
Console.WriteLine(s);
// "True"
#endregion
replacedert.AreEqual("True", s);
}
19
Source : ToObjectType.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
[Test]
public void Example()
{
#region Usage
JValue v1 = new JValue(true);
bool b = (bool)v1.ToObject(typeof(bool));
Console.WriteLine(b);
// true
int i = (int)v1.ToObject(typeof(int));
Console.WriteLine(i);
// 1
string s = (string)v1.ToObject(typeof(string));
Console.WriteLine(s);
// "True"
#endregion
replacedert.AreEqual("True", s);
}
19
Source : CreateJsonSchemaManually.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
public void Example()
{
#region Usage
JsonSchema schema = new JsonSchema();
schema.Type = JsonSchemaType.Object;
schema.Properties = new Dictionary<string, JsonSchema>
{
{ "name", new JsonSchema { Type = JsonSchemaType.String } },
{
"hobbies", new JsonSchema
{
Type = JsonSchemaType.Array,
Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } }
}
},
};
string schemaJson = schema.ToString();
Console.WriteLine(schemaJson);
// {
// "type": "object",
// "properties": {
// "name": {
// "type": "string"
// },
// "hobbies": {
// "type": "array",
// "items": {
// "type": "string"
// }
// }
// }
// }
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
Console.WriteLine(valid);
// true
#endregion
}
19
Source : JsonValidatingReaderAndSerializer.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
public void Example()
{
#region Usage
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
string json = @"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
validatingReader.Schema = JsonSchema.Parse(schemaJson);
IList<string> messages = new List<string>();
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
JsonSerializer serializer = new JsonSerializer();
Person p = serializer.Deserialize<Person>(validatingReader);
Console.WriteLine(p.Name);
// James
bool isValid = (messages.Count == 0);
Console.WriteLine(isValid);
// true
#endregion
}
19
Source : JTokenIsValid.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
public void Example()
{
#region Usage
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}");
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
IList<string> errorMessages;
bool valid = person.IsValid(schema, out errorMessages);
Console.WriteLine(valid);
// true
#endregion
}
19
Source : JTokenIsValidWithMessages.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
public void Example()
{
#region Usage
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
'name': null,
'hobbies': ['Invalid content', 0.123456789]
}");
IList<string> messages;
bool valid = person.IsValid(schema, out messages);
Console.WriteLine(valid);
// false
foreach (string message in messages)
{
Console.WriteLine(message);
}
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.
#endregion
}
19
Source : RefJsonSchemaResolver.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
public void Example()
{
#region Usage
string schemaJson;
JsonSchemaResolver resolver = new JsonSchemaResolver();
schemaJson = @"{
'id': 'person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'age': {'type':'integer'}
}
}";
JsonSchema personSchema = JsonSchema.Parse(schemaJson, resolver);
schemaJson = @"{
'id': 'employee',
'type': 'object',
'extends': {'$ref':'person'},
'properties': {
'salary': {'type':'number'},
'jobreplacedle': {'type':'string'}
}
}";
JsonSchema employeeSchema = JsonSchema.Parse(schemaJson, resolver);
string json = @"{
'name': 'James',
'age': 29,
'salary': 9000.01,
'jobreplacedle': 'Junior Vice President'
}";
JObject employee = JObject.Parse(json);
bool valid = employee.IsValid(employeeSchema);
Console.WriteLine(valid);
// true
#endregion
}
19
Source : PopulateObject.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
[Test]
public void Example()
{
#region Usage
Account account = new Account
{
Email = "[email protected]",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = @"{
'Active': false,
'Roles': [
'Expired'
]
}";
JsonConvert.PopulateObject(json, account);
Console.WriteLine(account.Email);
// [email protected]
Console.WriteLine(account.Active);
// false
Console.WriteLine(string.Join(", ", account.Roles.ToArray()));
// User, Admin, Expired
#endregion
replacedert.AreEqual("User, Admin, Expired", string.Join(", ", account.Roles.ToArray()));
}
19
Source : JValueCast.cs
with GNU General Public License v3.0
from OliverEGreen
with GNU General Public License v3.0
from OliverEGreen
[Test]
public void Example()
{
#region Usage
JValue v1 = new JValue("1");
int i = (int)v1;
Console.WriteLine(i);
// 1
JValue v2 = new JValue(true);
bool b = (bool)v2;
Console.WriteLine(b);
// true
JValue v3 = new JValue("19.95");
decimal d = (decimal)v3;
Console.WriteLine(d);
// 19.95
JValue v4 = new JValue(new DateTime(2013, 1, 21));
string s = (string)v4;
Console.WriteLine(s);
// 01/21/2013 00:00:00
JValue v5 = new JValue("http://www.bing.com");
Uri u = (Uri)v5;
Console.WriteLine(u);
// http://www.bing.com/
JValue v6 = JValue.CreateNull();
u = (Uri)v6;
Console.WriteLine((u != null) ? u.ToString() : "{null}");
// {null}
DateTime? dt = (DateTime?)v6;
Console.WriteLine((dt != null) ? dt.ToString() : "{null}");
// {null}
#endregion
replacedert.AreEqual("01/21/2013 00:00:00", s);
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
var myDouble = "5,4";
var turkishCulture = CultureInfo.GetCultureInfo("tr-TR");
Console.WriteLine(Double.Parse(myDouble, CultureInfo.InvariantCulture));
//54
Console.WriteLine(Double.Parse(myDouble, turkishCulture));
//5,4
var description = "Description";
Console.WriteLine(description.ToUpper() == "DESCRIPTION");
//true
Console.WriteLine(description.ToUpper().Equals("DESCRIPTION"));
//true
Console.WriteLine(Object.ReferenceEquals(description.ToUpper(), "DESCRIPTION"));
//false
Thread.CurrentThread.CurrentCulture = turkishCulture;
Console.WriteLine(description.ToUpper() == "DESCRIPTION");
//false DESCRİPTİON
Console.WriteLine(description.ToUpperInvariant() == "DESCRIPTION");
//true
Console.WriteLine(description.Equals("DESCRIPTION", StringComparison.OrdinalIgnoreCase));
//true
var dt = "05/01/2012";
Console.WriteLine(DateTime.Parse(dt).ToLongDateString());
Console.WriteLine(DateTime.Parse(dt).ToString("dddd, MMMM dd yyyy"));
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(DateTime.Parse(dt).ToString("dddd, MMMM dd yyyy"));
Console.WriteLine(DateTime.ParseExact(dt, "MM/dd/yyyy", turkishCulture).ToString("dddd, MMMM dd yyyy"));
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
var f = 0f;
var d = 0d;
var money = 0M;
Console.WriteLine(0.3 * 3.0 + 0.1 == 1.0);
Console.WriteLine(0.3M * 3.0M + 0.1M == 1.0M);
}
19
Source : 9ContinuationTasks.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
private static void ContinueWhenAny()
{
int number = 13;
Task<bool> taskA = Task.Factory.StartNew<bool>(() => number / 2 != 0);
Task<bool> taskB = Task.Factory.StartNew<bool>(() => (number / 2) * 2 != number);
Task<bool> taskC = Task.Factory.StartNew<bool>(() => (number & 1) != 0);
Task.Factory.ContinueWhenAny<bool>(new Task<bool>[] { taskA, taskB, taskC }, (task) =>
{
Console.WriteLine((task as Task<bool>).Result);
}
);
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void SetDemo()
{
{
HashSet<int> numbers = new HashSet<int>();
}
{
HashSet<int> numbers = new HashSet<int>()
{
1, 1, 2, 3, 5, 8, 11
};
}
{
HashSet<int> numbers = new HashSet<int>() { 11, 3, 8 };
numbers.Add(1);
numbers.Add(1);
numbers.Add(2);
numbers.Add(5);
PrintCollection(numbers);
Console.WriteLine(numbers.Contains(1));
Console.WriteLine(numbers.Contains(7));
numbers.Remove(1);
PrintCollection(numbers);
numbers.RemoveWhere(n => n % 2 == 0);
PrintCollection(numbers);
numbers.Clear();
PrintCollection(numbers);
}
{
HashSet<int> a = new HashSet<int>() { 1, 2, 5, 6, 9};
HashSet<int> b = new HashSet<int>() { 1, 2, 3, 4};
var s1 = new HashSet<int>(a);
s1.IntersectWith(b);
PrintCollection(s1);
var s2 = new HashSet<int>(a);
s2.UnionWith(b);
PrintCollection(s2);
var s3 = new HashSet<int>(a);
s3.ExceptWith(b);
PrintCollection(s3);
var s4 = new HashSet<int>(a);
s4.SymmetricExceptWith(b);
PrintCollection(s4);
}
{
HashSet<int> a = new HashSet<int>() { 1, 2, 5, 6, 9 };
HashSet<int> b = new HashSet<int>() { 1, 2, 3, 4 };
HashSet<int> c = new HashSet<int>() { 2, 5 };
Console.WriteLine(a.Overlaps(b));
Console.WriteLine(a.IsSupersetOf(c));
Console.WriteLine(c.IsSubsetOf(a));
}
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
{
var engine = new Tuple<string, int, double>("M270 Turbo", 1600, 75);
Console.WriteLine($"{engine.Item1} {engine.Item2 / 1000.0}l {engine.Item3}kW");
}
{
var engine = Tuple.Create("M270 Turbo", 1600, 75);
}
{
var engine = Tuple.Create(
"M270 DE16 LA R", 1595, 83, 73.7, 180, "gasoline", 2015,
Tuple.Create(75, 90, 115)
);
Console.WriteLine($"{engine.Item1} powers: {engine.Rest}");
}
{
var engine = new Tuple<string, int, int, double, int, string, int, Tuple<int, int, int>>(
"M270 DE16 LA R", 1595, 83, 73.7, 180, "gasoline", 2015,
new Tuple<int, int, int>(75, 90, 115));
Console.WriteLine($"{engine.Item1} powers: {engine.Rest}");
}
{
var engine = ("M270 Turbo", 1600, 75.0);
}
{
ValueTuple<string, int, double> engine = ("M270 Turbo", 1600, 75.0);
Console.WriteLine($"{engine.Item1} {engine.Item2 / 1000.0}l {engine.Item3}kW");
}
{
(string, int, double) engine = ("M270 Turbo", 1600, 75.0);
}
{
var engine = (Name: "M270 Turbo", Capacity: 1600, Power: 75.0);
Console.WriteLine($"{engine.Name} {engine.Capacity / 1000.0}l {engine.Power}kW");
}
{
(string Name, int Capacity, double Power) engine = ("M270 Turbo", 1600, 75.0);
Console.WriteLine($"{engine.Name} {engine.Capacity / 1000.0}l {engine.Power}kW");
}
{
(string Name, int Capacity, double Power) engine = (name: "M270 Turbo", cap: 1600, pow: 75.0);
Console.WriteLine($"{engine.Name} {engine.Capacity / 1000.0}l {engine.Power}kW");
}
{
var name = "M270 Turbo";
var capacity = 1600;
var engine = (name, capacity, 75);
Console.WriteLine($"{engine.name} {engine.capacity / 1000.0}l {engine.Item3}kW");
}
{
var engine = GetEngine();
Console.WriteLine($"{engine.Item1} {engine.Item2 / 1000.0}l {engine.Item3}kW");
}
{
var engine = GetEngine2();
Console.WriteLine($"{engine.Name} {engine.Capacity / 1000.0}l {engine.Power}kW");
}
{
var e1 = ("M270 Turbo", 1600, 75.0);
var e2 = (Name: "M270 Turbo", Capacity: 1600, Power: 75.0);
Console.WriteLine(e1 == e2);
}
{
(int, long) t1 = (1, 2);
(long, int) t2 = (1, 2);
Console.WriteLine(t1 == t2);
}
{
(string name, int capacity, double power) = GetEngine();
}
{
(var name, var capacity, var power) = GetEngine();
}
{
var (name, capacity, power) = GetEngine();
}
{
(var name, var capacity, double power) = GetEngine();
}
{
(var name, _, _) = GetEngine();
}
{
var engine = ("M270 Turbo", 1600, 75.0);
(string name, int capacity, double power) = engine;
}
{
var engine = new Engine("M270 Turbo", 1600, 75.0);
var (Name, Capacity, Power) = engine;
}
{
// error
// var engine = new Engine("M270 Turbo", 1600, 75.0);
// Console.WriteLine(engine == ("M270 Turbo", 1600, 75.0));
}
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
bool IsTrue(object value)
{
if (value is null) return false;
else if (value is 1) return true;
else if (value is true) return true;
else if (value is "true") return true;
else if (value is "1") return true;
return false;
}
void SetInMotion1(object vehicle)
{
if (vehicle is null)
throw new ArgumentNullException(
message: "Vehicle must not be null",
paramName: nameof(vehicle));
else if (vehicle is Airplane a)
a.Fly();
else if (vehicle is Bike b)
b.Ride();
else if (vehicle is Car c)
if (c.HasAutoDrive) c.AutoDrive();
else c.Drive();
else
throw new ArgumentException(
message: "Unexpected vehicle type",
paramName: nameof(vehicle));
}
void SetInMotion2(object vehicle)
{
switch (vehicle)
{
case Airplane a:
a.Fly();
break;
case Bike b:
b.Ride();
break;
case Car c:
if (c.HasAutoDrive) c.AutoDrive();
else c.Drive();
break;
case null:
throw new ArgumentNullException(
message: "Vehicle must not be null",
paramName: nameof(vehicle));
default:
throw new ArgumentException(
message: "Unexpected vehicle type",
paramName: nameof(vehicle));
}
}
void SetInMotion3(object vehicle)
{
switch (vehicle)
{
case Airplane a:
a.Fly();
break;
case Bike b:
b.Ride();
break;
case Car c when c.HasAutoDrive:
c.AutoDrive();
break;
case Car c:
c.Drive();
break;
case null:
throw new ArgumentNullException(
message: "Vehicle must not be null",
paramName: nameof(vehicle));
default:
throw new ArgumentException(
message: "Unexpected vehicle type",
paramName: nameof(vehicle));
}
}
void ExecuteCommand(string command)
{
switch (command)
{
case "add": /* add */ break;
case "del": /* delete */ break;
case "exit": /* exit */ break;
case var o when (o?.Trim().Length ?? 0) == 0:
/* do nothing */
break;
default:
/* invalid command */
break;
}
}
Console.WriteLine(IsTrue(null)); // False
Console.WriteLine(IsTrue(0)); // False
Console.WriteLine(IsTrue(1)); // True
Console.WriteLine(IsTrue(true)); // True
Console.WriteLine(IsTrue("true")); // True
Console.WriteLine(IsTrue("1")); // True
Console.WriteLine(IsTrue("demo")); // False
SetInMotion1(new Car());
SetInMotion2(new Car());
SetInMotion3(new Car());
ExecuteCommand("add");
ExecuteCommand("quit");
ExecuteCommand(null);
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
{
var text = "123۳۲١८৮੪૯୫୬१७੩௮௫౫೮൬൪๘໒໕២៧៦᠖";
var match = Regex.Match(text, @"\d+");
Console.WriteLine($"[{match.Index}..{match.Length}]: {match.Value}");
}
{
var text = "123۳۲١८৮੪૯୫୬१७੩௮௫౫೮൬൪๘໒໕២៧៦᠖";
var match = Regex.Match(text, @"\d+", RegexOptions.ECMAScript);
Console.WriteLine($"[{match.Index}..{match.Length}]: {match.Value}");
}
var pattern = @"(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})";
{
var success = Regex.IsMatch("2019-12-25", pattern);
Console.WriteLine(success);
}
{
var regex = new Regex(pattern);
var success = regex.IsMatch("2019-12-25");
Console.WriteLine(success);
}
{
var success = Regex.IsMatch(
"2019-12-25",
@"^(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})$",
RegexOptions.ECMAScript,
TimeSpan.FromMilliseconds(1));
Console.WriteLine(success);
}
{
var text = "2019-12-25";
var match = Regex.Match(text, pattern);
Console.WriteLine(match.Value);
Console.WriteLine($"{match.Groups[1]}.{match.Groups[2]}.{match.Groups[3]}");
}
{
var text = "2019-12-25";
var regex = new Regex(@"^(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})$");
var match = regex.Match(text);
Console.WriteLine(match.Value);
}
{
var text = "2019-05-01,2019-5-9,2019-12-25,2019-13-21";
var matches = Regex.Matches(text, @"(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})");
foreach (Match match in matches)
Console.WriteLine(match);
for (int i = 0; i < matches.Count; ++i)
if (matches[i].Success)
Console.WriteLine(
$"[{matches[i].Index}..{matches[i].Length}]={matches[i].Value}");
}
{
var text = "2019-05-01,2019-5-9,2019-12-25,2019-13-21";
var matches = Regex.Matches(text, @"(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})");
foreach (Match match in matches)
Console.WriteLine(match.Groups[1].Value);
for (int i = 0; i < matches.Count; ++i)
if (matches[i].Success)
Console.WriteLine(
$"[{matches[i].Index}..{matches[i].Length}]={matches[i].Groups[1].Value}");
}
{
var text = "2019-05-01\n2019-5-9\n2019-12-25\n2019-13-21\n2019-1-32";
var matches = Regex.Matches(text, @"^(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})$", RegexOptions.Multiline);
foreach (Match match in matches)
{
Console.WriteLine(
$"[{match.Index}..{match.Length}]={match.Value}");
}
}
{
var text = "2019-05-01\n2019-5-9\n2019-12-25\n2019-13-21";
var matches = Regex.Matches(
text,
@"^(\d{4})-(1[0-2]|0[1-9]|[1-9]{1})-(3[01]|[12][0-9]|0[1-9]|[1-9]{1})$",
RegexOptions.Multiline,
TimeSpan.FromMilliseconds(1));
foreach (Match match in matches)
{
Console.WriteLine($"{match.Groups[1]}-{match.Groups[2]}-{match.Groups[3]}");
}
}
{
var text = "2019-12-25";
var match = Regex.Match(text, @"^(?<year>\d{4})-(?<month>1[0-2]|0[1-9]|[1-9]{1})-(?<day>3[01]|[12][0-9]|0[1-9]|[1-9]{1})$");
Console.WriteLine($"{match.Groups["year"]}-{match.Groups["month"]}-{match.Groups["day"]}");
}
{
var text = "2019-12-25";
var result = Regex.Replace(text, pattern, m => $"{m.Groups[2]}/{m.Groups[3]}/{m.Groups[1]}");
Console.WriteLine(result);
}
}
19
Source : Program.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void Main(string[] args)
{
{
var path = @"c:\Windows\System32\mmc.exe";
Console.WriteLine(Path.HasExtension(path));
Console.WriteLine(Path.IsPathFullyQualified(path));
Console.WriteLine(Path.IsPathRooted(path));
Console.WriteLine(Path.GetPathRoot(path));
Console.WriteLine(Path.GetDirectoryName(path));
Console.WriteLine(Path.GetFileName(path));
Console.WriteLine(Path.GetFileNameWithoutExtension(path));
Console.WriteLine(Path.GetExtension(path));
Console.WriteLine(Path.ChangeExtension(path, ".dll"));
}
{
var path1 = Path.Combine(@"c:\temp", @"sub\data.txt");
Console.WriteLine(path1); // c:\temp\sub\data.txt
var path2 = Path.Combine(@"c:\temp\sub", @"..\", "log.txt");
Console.WriteLine(path2); // c:\temp\sub\..\log.txt
}
{
var temp = Path.GetTempPath();
var name = Path.GetRandomFileName();
var path1 = Path.Combine(temp, name);
Console.WriteLine(path1);
var path2 = Path.GetTempFileName();
Console.WriteLine(path2);
File.Delete(path2);
}
{
var dir = new DirectoryInfo(@"C:\Program Files (x86)\Microsoft SDKs\Windows\");
Console.WriteLine($"Full name : {dir.FullName}");
Console.WriteLine($"Name : {dir.Name}");
Console.WriteLine($"Parent : {dir.Parent}");
Console.WriteLine($"Root : {dir.Root}");
Console.WriteLine($"Created : {dir.CreationTime}");
Console.WriteLine($"Attributes: {dir.Attributes}");
foreach(var subdir in dir.EnumerateDirectories())
{
Console.WriteLine(subdir.Name);
}
}
{
var dir = new DirectoryInfo(@"C:\Temp\Dir\Sub");
Console.WriteLine($"Exists: {dir.Exists}");
dir.Create();
var sub = dir.CreateSubdirectory(@"sub1\sub2\sub3");
Console.WriteLine(sub.FullName);
sub.Delete();
}
{
var dir = new DirectoryInfo(@"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\");
foreach(var file in dir.GetFiles("t*.exe"))
{
Console.WriteLine($"{file.Name} [{file.Length}] [{file.Attributes}]");
}
}
{
var path = @"C:\Temp\Dir\Sub";
Console.WriteLine($"Exists: {Directory.Exists(path)}");
Directory.CreateDirectory(path);
var sub = Path.Combine(path, @"sub1\sub2\sub3");
Directory.CreateDirectory(sub);
Directory.Delete(sub);
Directory.Delete(path, true);
}
{
var file = new FileInfo(@"C:\Windows\explorer.exe");
Console.WriteLine($"Name: {file.Name}");
Console.WriteLine($"Extension: {file.Extension}");
Console.WriteLine($"Full name: {file.FullName}");
Console.WriteLine($"Length: {file.Length}");
Console.WriteLine($"Attributes: {file.Attributes}");
Console.WriteLine($"Creation: {file.CreationTime}");
Console.WriteLine($"Last access:{file.LastAccessTime}");
Console.WriteLine($"Last write: {file.LastWriteTime}");
}
{
PrintContent(@".\..\..\..\");
}
{
var path = @"C:\Temp\Dir\demo.txt";
using (var file = new StreamWriter(File.Create(path)))
{
file.Write("This is a demo");
}
File.WriteAllText(path, "This is a demo");
File.AppendAllText(path, "1st line");
File.AppendAllLines(path, new string[]{ "2nd line", "3rd line"});
string text = File.ReadAllText(path);
string[] lines = File.ReadAllLines(path);
File.Delete(path);
}
}
See More Examples