How to get the index of a string value in a list, and assign it to a field in linq

0 votes
asked Jun 29, 2016 by fox-u

I am new to linq, I am writing linq like:

temp = mdl.T57.Select(v => new TestMDTDataSource()
{
    StatYear = v.StatYear,
    StatM = v.StatM,
    StatMonth = v.StatMonth,
    TransportMode = null,
    TradeType = v.TradeType,
    Country = v.Country,
    ItemCode = null,
    ItemDesc = null,
    ItemUnit = null,
    TradeValue = v.TradeValue,
    TradeQty = null,
    YtoY = v.YtoY,
    TopNIndex = (Nullable<int>)TopNCountryList.IndexOf(v.Country + 1)
});

but I got "LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String)' method, and this method cannot be translated into a store expression"

The TopNCountryList variable is a list of string. I first select the data in Dec. of 2014, and ordered them by TradeValue in descending order. So I got a list of country, and that is TopNCountryList. My final return value is temp.ToList() which is a list of custom object (All the properties are listed in the linq above, and this object will be used by other functions for different query results. That's why I set TopNIndex to be Nullable.). I can get the result if I change "TopNIndex = (Nullable)TopNCountryList.IndexOf(v.Country + 1)" to "TopNIndex = (Nullable) 1" I want to assign an integer value to TopNIndex according to the TradeValue order in Dec. of 2014 to all the data (from Jan. of 2014 to Dec. of 2014) Does linq support IndexOf(System.String)? Or did I make anything wrong? Or ... is there any other simple way?

1 Answer

0 votes
answered Jun 29, 2016 by ad-net

If you are running this against database, you'll get that error. One simple way would be not to populate that property when you're executing the query. But after execution, you can run it in memory.

temp = mdl.T57.Select(v => new TestMDTDataSource()
{
    StatYear = v.StatYear,
    StatM = v.StatM,
    StatMonth = v.StatMonth,
    TransportMode = null,
    TradeType = v.TradeType,
    Country = v.Country,
    ItemCode = null,
    ItemDesc = null,
    ItemUnit = null,
    TradeValue = v.TradeValue,
    TradeQty = null,
    YtoY = v.YtoY  
}).ToList();
temp.ForEach(v=>v.TopNIndex = (Nullable<int>)TopNCountryList.IndexOf(v.Country)+1);
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...