簡體   English   中英

如何使用LINQ C#基於多個條件更新列表

[英]How to update a list based on more than one Condition using LINQ C#

我有一個用豎線符號“ | ”分隔的字符串,我在分割字符串並轉換為List<string> 如果List<string>包含字符串“ Fax ”,則使用嵌入式Single LINQ語句將該字符串替換為“ A ”,與字符串“ phone ”相同,替換為字符串“ B”。 不要嘗試替換基本字符串str

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

因此,我的預期輸出應為

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

使用select轉換輸出。

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

它是這樣的:

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();

嘗試這個:

        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();

我敢肯定有更好的解決方案,但這是我的看法:

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();

基於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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM