首页 > 解决方案 > 从列表中获取和重新分配值

问题描述

我正在遍历一个列表,当在列表中找到特定值时,我想将索引号设置为 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 是由程序从文件中读取的,但为了简单起见,此处说明。我正在从多个文件中读取,每个文件我们可以从单个文件中获得以下值

  1. CN
  2. PT
  3. FR
  4. FI

sequenceNumber 如果在列表中找到 EN ,我想将值 1 分配给。接下来的值将是 2 代表 DE,3 代表 PT,4 代表 FR,5 代表 FI 等等(取决于列表是否更长)。如果在列表中找到 EN,则其值必须为 1。如果列表中没有 EN,那么我们应该从值 2 开始。这意味着不允许其他国家有值 1。

标签: c#

解决方案


如何首先检查列表中的“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++;
    }
}

推荐阅读