【问题标题】:How to filter strings from an array of objects如何从对象数组中过滤字符串
【发布时间】:2017-02-08 23:46:32
【问题描述】:

我有一个这样的对象数组:

 object[] test = {
        "Rock Parrot",
        "Crimson Rosella",
        "Regent Parrot",
        "Superb Parrot",
        "Red Lory",
        "African Emerald Cuckoo",
        1,2,3


};

我如何过滤这个数组并只得到一个字符串数组。

谢谢

【问题讨论】:

    标签: c# arrays string collections


    【解决方案1】:

    你可以这样做:

    var stringsOnly = test.OfType<String>().ToArray()
    

    【讨论】:

    • 这对我不起作用。会不会是 OfType 少了括号?
    • 太好了@Blorgbeard ...我也试过这个 var stringOnly= Array.FindAll(test, x => x is string);你认为哪一个在资源上更好。
    • 我想实际上两者都“足够快”。如果你担心,我建议你race your horses:P
    【解决方案2】:
    string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();
    

    【讨论】:

    • 欢迎来到堆栈溢出 :-) 请看How to Answer。您应该提供一些信息为什么您的代码可以解决问题。纯代码答案对社区没有用处。
    • 感谢 Blorgbeard - 已修复
    【解决方案3】:

    你可以这样做:

    object[] test = {
            "Rock Parrot",
            "Crimson Rosella",
            "Regent Parrot",
            "Superb Parrot",
            "Red Lory",
            "African Emerald Cuckoo",
            1,2,3};
    
    List<string> s = new List<string>();
    
    foreach (var item in test)
    {
    
        if (typeof(string) == item.GetType())
            s.Add(item.ToString());
    }
    

    如果您运行此代码,则响应:

    Rock Parrot
    Crimson Rosella
    Regent Parrot
    Superb Parrot
    Red Lory
    African Emerald Cuckoo
    

    你可以转换成数组:

    var a = s.ToArray();
    

    【讨论】:

    • 如果数组中有任何null 值,这将崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2019-04-04
    • 2022-01-13
    • 2015-03-24
    • 2021-12-15
    • 2020-08-15
    相关资源
    最近更新 更多