-4

次の項目を含むリストがあります。

バンドル/リリース/米国---NL
バンドル/リリース/英国---米国

リストアイテムでサブストリング(「US」または「UK」)を検索したい。

var testVar = (from r in ghh
    where (r.Substring(r.LastIndexOf('/') + 1, 
                       (r.Length - (r.IndexOf("---")    + 3)))) == "US"
    select r).ToList();

if ( testVar != null)
{
    //print item is present
}

ghhリスト名です)

しかしtestVar、常に表示されていnullます。なんで?

4

3 に答える 3

1

なぜ使用しないのですか(リストが単に文字列のリストであると仮定して):

 var items = (from r in ghh where r.Contains("UK") || r.Contains("US") select r).ToList();
于 2012-09-19T10:49:17.177 に答える
1

別の方法を試してください:

testVar.Where(x => {
    var country = x.Split('/').Last()
              .Split(new[] { "---" }, StringSplitOptions.RemoveEmptyEntries)
              .First();

    return country == "US" || country == "UK";
}).ToList();
于 2012-09-19T10:55:32.793 に答える
1

ある状況はありませtestVarnull

これを説明するためのコードを次に示します。実行する前に、必ず出力ビューをアクティブにしてください...表示->出力

発生する可能性がある唯一のことは、linqクエリが後で実行され、linqがクエリを試行した時点でghhがnullであったため、null例外が発生することです。Linqは必ずしも即座に実行されるわけではありません。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            CallAsExpected();
            CallWithNull();
            CallNoHits();
            Console.WriteLine("Look at Debug Output");
            Console.ReadKey();
        }

        private static void CallNoHits()
        {
            TryCall(new List<string> {
                "UK foo",
                "DE bar"
            });
        }

        private static void CallWithNull()
        {
            TryCall(null);
        }

        private static void CallAsExpected()
        {
            TryCall(new List<string> {
                "US woohooo",
                "UK foo",
                "DE bar",
                "US second",
                "US third"
            });
        }

        private static void TryCall(List<String> ghh)
        {
            try
            {
                TestMethod(ghh);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

        private static void TestMethod(List<String> ghh)
        {
            if (ghh == null) Debug.WriteLine("ghh was null");

            var testVar = (from r in ghh
                           where (r.Contains("US"))
                           select r);

            Debug.WriteLine(String.Format("Items Found: {0}", testVar.Count()));

            if (testVar == null) Debug.WriteLine("testVar was null");

            foreach (String item in testVar)
            {
                Debug.WriteLine(item);
            }
        }
    }
}
于 2012-09-19T11:16:15.310 に答える