CSHARP_1001_NOTES Telegram 714
Трюк: добавление элементов в словарь со списками через `??=`


var dict = new Dictionary<string, List<int>>();
string key = "numbers";
int item = 42;

// Обычный способ:
if (!dict.TryGetValue(key, out var list))
{
list = new List<int>();
dict[key] = list;
}
list.Add(item);

// Короткий трюк:
(dict[key] ??= new List<int>()).Add(item);


Разбор:

- При обращении к dict[key] отсутствующий ключ вернёт default(List<int>), то есть null.

- Оператор ??= проверяет левую часть на null и, если она null, присваивает справа новое значение.

- В нашем случае, если dict[key] был null, создаётся новый List<int> и сразу сохраняется в словаре.

- После этого метод .Add(item) вызывается уже на существующем списке.

- В результате за одну строчку мы и проверили наличие, и создали новый список при необходимости, и добавили элемент.



tgoop.com/csharp_1001_notes/714
Create:
Last Update:

Трюк: добавление элементов в словарь со списками через `??=`


var dict = new Dictionary<string, List<int>>();
string key = "numbers";
int item = 42;

// Обычный способ:
if (!dict.TryGetValue(key, out var list))
{
list = new List<int>();
dict[key] = list;
}
list.Add(item);

// Короткий трюк:
(dict[key] ??= new List<int>()).Add(item);


Разбор:

- При обращении к dict[key] отсутствующий ключ вернёт default(List<int>), то есть null.

- Оператор ??= проверяет левую часть на null и, если она null, присваивает справа новое значение.

- В нашем случае, если dict[key] был null, создаётся новый List<int> и сразу сохраняется в словаре.

- После этого метод .Add(item) вызывается уже на существующем списке.

- В результате за одну строчку мы и проверили наличие, и создали новый список при необходимости, и добавили элемент.

BY C# 1001 notes


Share with your friend now:
tgoop.com/csharp_1001_notes/714

View MORE
Open in Telegram


Telegram News

Date: |

As the broader market downturn continues, yelling online has become the crypto trader’s latest coping mechanism after the rise of Goblintown Ethereum NFTs at the end of May and beginning of June, where holders made incoherent groaning sounds and role-played as urine-loving goblin creatures in late-night Twitter Spaces. The group also hosted discussions on committing arson, Judge Hui said, including setting roadblocks on fire, hurling petrol bombs at police stations and teaching people to make such weapons. The conversation linked to arson went on for two to three months, Hui said. Hui said the messages, which included urging the disruption of airport operations, were attempts to incite followers to make use of poisonous, corrosive or flammable substances to vandalize police vehicles, and also called on others to make weapons to harm police. Telegram is a leading cloud-based instant messages platform. It became popular in recent years for its privacy, speed, voice and video quality, and other unmatched features over its main competitor Whatsapp. The initiatives announced by Perekopsky include monitoring the content in groups. According to the executive, posts identified as lacking context or as containing false information will be flagged as a potential source of disinformation. The content is then forwarded to Telegram's fact-checking channels for analysis and subsequent publication of verified information.
from us


Telegram C# 1001 notes
FROM American