c# - 从列表中获取和重新分配值
问题描述
我正在遍历一个列表,当在列表中找到特定值时,我想将索引号设置为 1。我想从 1 获取 sequenceNumber 或 /index 计数。如果EN在列表中,我想将序列号设置为 1,其余值应从 2 开始。国家/地区列表是从文件中读取的,可能更多。这是我的代码
public static List<TResult> GetValues<TResult>(Func<string, string, int, TResult> createType)
where TResult : class
{
var dynamicCountryList = new List<string>(new [] {"DE", "EN", "PT", "FR"})
// this list is dynamic and can be populated by the program.
var staticCountryList = new List<string>(); // created this to get the sequence values
var numberOfCountries= countryList.Count;
foreach (var country in dynamicCountryList)
{
if (!staticCountryList.Contains(country)
{
staticCountryList.Add(country)
}
var sequenceNumber = numberOfCountries == 1 && country == "EN"
? staticCountryList.IndexOf("EN") + 1
: numberOfCountries == 1 && country != "EN"
? 2
: numberOfCountries > 1 && country!= "EN" && staticCountryList.IndexOf(country) < 1
? sequenceNumberList.IndexOf(country) + 3
: numberOfCountries> 1 && country!= "EN" && staticCountryList.IndexOf(lang) == 1
? staticCountryList.IndexOf(country) + 1
: staticCountryList.IndexOf(country);
result.Add(createType(string.Empty, string.Empty, sequenceNumber));
}
即使EN是列表中的第 20 项,我也想分配一个值 1,其余的可以按照它们添加到列表中的方式排序(如 1、2、3、4 ......等)。有什么帮助吗?
编辑*
基本上 dynamicCountryList 是由程序从文件中读取的,但为了简单起见,此处说明。我正在从多个文件中读取,每个文件我们可以从单个文件中获得以下值
- 德
- CN
- PT
- FR
- FI
sequenceNumber
如果在列表中找到 EN ,我想将值 1 分配给。接下来的值将是 2 代表 DE,3 代表 PT,4 代表 FR,5 代表 FI 等等(取决于列表是否更长)。如果在列表中找到 EN,则其值必须为 1。如果列表中没有 EN,那么我们应该从值 2 开始。这意味着不允许其他国家有值 1。
解决方案
如何首先检查列表中的“EN”,然后遍历它的其余部分?
public static List<TResult> GetValues<TResult>(Func<string, string, int, TResult> createType)
where TResult : class
{
var dynamicCountryList = new List<string>(new[] { "DE", "EN", "PT", "FR" })
// this list is dynamic and can be populated by the program.
if (dynamicCountryList.Contains("EN"))
{
result.Add(createType(string.Empty, string.Empty, 1));
}
int sequenceNumber = 2;
foreach (var country in dynamicCountryList)
{
// "EN" condition already handled, just go on to the next one.
if (country == "EN")
{
continue;
}
result.Add(createType(string.Empty, string.Empty, sequenceNumber));
sequenceNumber++;
}
}
推荐阅读
- git - 成功推送到GitHub,但是没有记录
- mobile - 验证无法获取测试状态,错误:无法获取测试状态:Bitrise 中的 INVALID(TEST_SAME_AS_APP)
- ios - 如何在 DatePicker 上进行验证?
- javascript - 在 JavaScript 中合并多个 csv 文件?
- performance - Kentico CMS 性能
- python - 从 csv 文件创建字典
- ruby-on-rails - 如何在 Rails 中使用 LIKE 进行搜索
- ios - 如何在 NavigationController 和 UITabbar 上方显示 UIView?
- python - python多线程与队列按顺序运行而不是并行
- html - CSS中的元素圆心