2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.NET 9 Preview 1における2つの機能

Posted at

Jsonインデント

Json出力時のインデント制御が追加されました。以下のコードのようになります:

using System.Text.Json;
var options = new JsonSerializerOptions{
    // インデントを有効にする
    WriteIndented = true,
    // インデント文字
    IndentCharacter = ' ',
    // インデントサイズ
    IndentSize = 6,
    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
string json = JsonSerializer.Serialize(
    new { Name = "张三", Age=20, Sex="男" },
    options    
);Console.WriteLine(json);

サポートされているインデント文字はスペースと水平タブ(Tabキー)のみで、他の文字を使用するとエラーが発生します。以下は出力結果です。

{
      "Name": "张三",
      "Age": 20,
      "Sex": "男"
}

JsonSerializerOptionsには既にJsonSerializerOptions.Defaultの設定が提供されており、新たにJsonSerializerOptions.Webが加わりました。デフォルトはキャメルケース命名規則です。

var webJson = JsonSerializer.Serialize(
    new { UserName = "gsw", Password="123456" },
    JsonSerializerOptions.Web // キャメルケース命名規則がデフォルト。
    );Console.WriteLine(webJson);

結果:

{"userName":"gsw","password":"123456"}

Linq拡張メソッドCountByとAggregateBy

CountByでは、キーが同じものを合計し、KeyValueコレクションを返します。MaxByとMinByは、集合全体で最も多くおよび最も少ないKeyValueを取得します。同じものがある場合は、最初のものを取得します。

var sourceText = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices amet diam.""";Console.WriteLine(sourceText);

var KVs = sourceText
    .Split(new char[] { ' ', '.', ',','\r','\n' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(word => word.ToLowerInvariant())
    .CountBy(word => word);foreach (var item in KVs){    Console.WriteLine(item.Key + ":" + item.Value);}Console.WriteLine("-------------------------");var mostFrequentWord = KVs.MaxBy(pair => pair.Value);Console.WriteLine(mostFrequentWord.Key + ":" + mostFrequentWord.Value);Console.WriteLine("-------------------------");mostFrequentWord = KVs.MinBy(pair => pair.Value);Console.WriteLine(mostFrequentWord.Key + ":" + mostFrequentWord.Value);

実行結果:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.Sed non risus. Suspendisse lectus tortor, dignissim sit amet,adipiscing nec, ultricies sed, dolor. Cras elementum ultrices amet diam.
lorem:1
ipsum:1
dolor:2
sit:2
amet:3
consectetur:1
adipiscing:2
elit:1
sed:2
non:1
risus:1
suspendisse:1
lectus:1
tortor:1
dignissim:1
nec:1
ultricies:1
cras:1
elementum:1
ultrices:1
diam:1
-------------------------
amet:3
-------------------------
lorem:1

AgregateByでは、KeyValueコレクションに対して合計計算を行います。

var orders = new Order[] {
       new Order("zs", 1,DateTime.Now),
       new Order("ls", 2,DateTime.Now),
       new Order("ww", 3,DateTime.Now),
       new Order("zs", 4,DateTime.Now),
       new Order("ls", 5,DateTime.Now),
       new Order("ww", 6,DateTime.Now),
    };var kvs = orders.AggregateBy(
     keySelector: word => word.OrderUser,
        seed: 0m,
        (orderAmount, order) => orderAmount + order.OrderAmount        
        );foreach (var item in kvs){    Console.WriteLine(item.Key + ":" + item.Value);}

record Order(string OrderUser, decimal OrderAmount, DateTime OrderTime);
実行結果:

zs:5
ls:7
ww:9

(Translated by GPT)

元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247487761&idx=1&sn=7e8110792142cd1888ce681509e44c6d&chksm=9f004e3ba877c72de46e18474a5e6f3208a06c0d8c98e49a1f124ac2b4c658bdf5c05f6a1395&token=1232314813&lang=zh_CN#rd

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?