gpt4 book ai didi

c# - Linq 查询 Group By 和 contains

转载 作者:行者123 更新时间:2023-12-02 08:03:11 24 4
gpt4 key购买 nike

我有一个字符串列表,它是货币代码

var currencyCode = new List<string>() { "USD", "SGD", "KWD", "BHD", "LYD" };

我还有另一个复杂的对象。

 var rate = new List<Rate>()
{
new Rate() { CurrencyName = "USD (SMALL)",CurrencyCode = "USD SMALL",BranchName="Branch1"},
new Rate() { CurrencyName = "SGD BIG",CurrencyCode = "SGD BIG",BranchName="Branch1"},
new Rate() { CurrencyName = "KUWAIT DINAR",CurrencyCode = "KWD",BranchName="Branch1"},
new Rate() { CurrencyName = "USD BIG (100,50)",CurrencyCode = "USD BIG",BranchName="Branch1"},
new Rate() { CurrencyName = "USD MEDIUM (10,20)",CurrencyCode = "USD MEDIUM",BranchName="Branch1"},
};

我将在下面的列表中找到匹配的货币:

var matchedCurrency = from c in rate
where currency.Any(w => c.CurrencyCode.Contains(w))
select c;

我想要的是匹配的货币列表应该按货币代码分组。

我尝试了以下方法,但没有成功。

 var Grp = rate.GroupBy(item => currency.Any(w => item.CurrencyCode.Contains(w)))
.Select(group => new
{
group.Key,
DataList = group.ToList()
});

我不明白我实际上失踪了。我通过各种方式尝试过。

我知道我可以遍历rate并插入另一个对象。但这看起来不太好,我想通过使用 Linq 来做到这一点。但我没能达到这个目的。

输出将与此对象一起显示:

public class CurrencyMap
{
public string Code { get; set; }

public List<Currency> currency { get; set; }
}
public class Currency
{
public string CurrencyName { get; set; }
public string CurrencyCode { get; set; }
public string BranchName { get; set; }
}
enter code here

编辑:

我一开始错过了这些事情,但如果在费率中找不到匹配的代码,我也需要有空列表。

在费率中没有“BHD”、“LYD”的匹配列表。但我还需要带有代码“BHD”、“LYD”的空列表

最佳答案

首先选择匹配的货币代码,然后按所选代码进行分组。

var groupedRates = rate
.Select(r => new
{
rate = r,
code = currencyCode.FirstOrDefault(c => r.CurrencyCode.Contains(c))
})
.GroupBy(x => x.code, x => x.rate); //maybe you don't want to throw away the resolved code like I do in the element selector...

编辑:我想我有点专注于分组方面。由于您想要包含所有货币代码并提到特定的输出结构,因此无需考虑分组,只需选择结果即可:

var groupedRatesList = currencyCode
.Select(c => new CurrencyMap
{
Code = c,
currency = rate
.Where(x => x.CurrencyCode.Contains(c))
.Select(x => new Currency
{
BranchName = x.BranchName,
CurrencyCode = x.CurrencyCode, // or maybe you want to insert c here?
CurrencyName = x.CurrencyName
})
.ToList()
})
.ToList();

关于c# - Linq 查询 Group By 和 contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com