小编Jes*_*ker的帖子

将两个foreach语句合二为一

我有以下foreach语句,我想将这些语句转换为linq查询。

var equalityGroup= new Dictionary<string, List<string>();
var firstGroup = new Dictionary<string, List<string>();
var request = new List<Request>();

foreach(var element in request) 
{
    var key = element.Number;
    if (!equalityGroup.ContainsKey(key))
    {
        equalityGroup.Add(key, new List<string>());
    }

    foreach(var item in firstGroup)
    {
        var query = item.Value.FindAll(y => y ==element.Id);
        if (query.Any())
        {
            equalityGroup[key].AddRange(query);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以给我一个有关Linq的好榜样,该榜样可以像上面所说的那样工作吗?

c# linq

5
推荐指数
0
解决办法
127
查看次数

我可以将两个函数逻辑合而为一,以便可以重用-SOLID Dry C#

我想将两个功能结合在一起,然后再使用,以便遵循干式代码的SOLID原则。我有两个不同的列表,都包含id作为其对象的属性。我想组合此逻辑并给另一个方法参数,以便它将执行重复的逻辑。

public static bool IsParfumesStyleValid(string style, List<Parfumes> parfumes)
{
    foreach (var parfume in parfumes)
    {
        var matchNumbersInDecimal = Regex.IsMatch(parfume.Id, "^(\\d*\\.)\\d+");
        var matchFullNumbers = Regex.IsMatch(parfume.Id, "^\\d+$");
        var matchNumbersWithHalfs = Regex.IsMatch(parfume.Id, "^[1-9][0-9]*\\/[1-9][0-9]*");

        if ((style == "decimal" && !matchNumbersInDecimal)
            || (style == "full" && !matchFullNumbers)
            || (style == "numbersWithHalfs" && !matchNumbersWithHalfs))
        {
            return false;
        }
    }

    return true;
}


public static bool IsCosmeticsStyleValid(string style, List<Cosmetics> cosmetics)
{
    foreach (var item in cosmetics)
    {
        var matchNumbersInDecimal = Regex.IsMatch(item.Id, "^(\\d*\\.)\\d+");
        var matchFullNumbers = Regex.IsMatch(item.Id, "^\\d+$"); …
Run Code Online (Sandbox Code Playgroud)

c#

2
推荐指数
1
解决办法
70
查看次数

如何使用 NewtonSoft 库忽略空数组元素

我有以下代码:

public City[] Cities { get; set; }
Run Code Online (Sandbox Code Playgroud)

在 City 类中,我有两个属性

public string Name { get; set; }
public string Code { get; set; }
Run Code Online (Sandbox Code Playgroud)

当出现此Cities字段为空的请求时,我想用 Newtonsoft 隐藏它。

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public City[] Cities { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是我试过的这段代码不起作用,因为 Cities它不是空的,而是空的,并且请求在这个数组中总是有两个属性。

在这种情况下我应该如何使用 Newtonsoft?这里需要的对象是否有任何额外的检查?

c# json.net

2
推荐指数
1
解决办法
2860
查看次数

标签 统计

c# ×3

json.net ×1

linq ×1