如何使用LINQ C#基于多个条件更新列表

时间:2016-03-15 12:07:14

标签: c# string linq list

我有一个带管道符号的字符串&#34; |&#34;分开后,我将字符串拆分并转换为List<string>。如果List<string>包含字符串&#34; 传真&#34;,则将字符串替换为&#34; A &#34;与字符串&#34; 电话&#34;相同字符串&#34; B&#34;使用内联单LINQ语句。不要尝试替换基本字符串str

string str = "fax|mobile|phone";
str.Split('|').Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone").ToList();

所以,我的预期输出应该是

List<string>() {"A", "B"}

5 个答案:

答案 0 :(得分:2)

使用select转换输出。

        str.Split('|')
           .Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone")
           .Select(x=> x=="fax"? "A" : x=="phone"? "B" : x)
           .ToList();

答案 1 :(得分:1)

这是这样的:

string str = "fax|mobile|phone";
var result = str.Split('|').Select(i => 
    string.Equals(i, "fax", StringComparison.InvariantCultureIgnoreCase) ? "A" : 
    string.Equals(i, "phone", StringComparison.InvariantCultureIgnoreCase) ? "B" : 
    null)
    .Where(i => i != null)
    .ToList();

请不要更改字符串的大小写以进行比较。有很好的方法可以进行不区分大小写的比较。

这段代码变得非常难以理解。更好的解决方案是使用单独的Dictionary<,>

var dict = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
dict.Add("fax", "A");
dict.Add("phone", "B");

string str = "fax|mobile|phone";

var result = str.Split('|').Select(i => {
        string r;
        dict.TryGetValue(i, out r);
        return r;
    })
    .Where(i => i != null)
    .ToList();

答案 2 :(得分:1)

试试这个:

        string str = "fax|mobile|phone";
        var result = str.Split('|').Where(i => i.ToLowerInvariant() == "fax" || i.ToLowerInvariant() == "phone").Select(i =>
            i.ToLowerInvariant() == "fax" ? "A" : "B").ToList();

答案 3 :(得分:1)

我确信有更好的解决方案,但这是我的看法:

string str = "fax|mobile|phone";
List<string> list = str.Split('|')
                       .Select(x => x.ToLowerInvariant() == "fax" ? "A" : x.ToLowerInvariant() == "phone" ? "B" : null)
                       .ToList();
list.Remove(null);

list.Remove(null);可以替换为Where子句以获得一个班轮:

List<string> list = str.Split('|')
                       .Select(x => x.ToLowerInvariant() == "fax" ? "A" : x.ToLowerInvariant() == "phone" ? "B" : null)
                       .Where(x => x != null)
                       .ToList();

一个好主意是使用单独的方法来获取匹配的字符串:

public string GetMatch(string s)
{
    // Easier to maintain
    return s.ToLowerInvariant() == "fax" ? "A" : s.ToLowerInvariant() == "phone" ? "B" : null;
}

然后做:

List<string> list = str.Split('|')
                       .Select(x => GetMatch(x))
                       .Where(x => x != null)
                       .ToList();

答案 4 :(得分:0)

基于xanatos解决方案

var string s = string.Empty;
var dic = new Dictionary<string,string>(StringComparer.InvariantCultureIgnoreCase)
{
  {"fax","a"},{"phone","b"}
}
var result = (from w in str.split('|') where dic.TryGetValue(w, out s) select s).toList();
相关问题