Używam LINQ
, aby wybrać nowy obiekt twoWords
do obiektu List
tego obiektu i ustawić wartości przez wywołanie funkcji/metody.LINQ wybierz do nowego obiektu, ustawiając wartości obiektu w funkcji
Proszę sprawdzić, czy to ma sens, bardzo to uprośniłem. Naprawdę chcę użyć instrukcji linq from
select
.
Pierwsza funkcja w GOGO
będzie działać, drugi nie powiedzie się (nie wykonują to samo zadanie, chociaż)
// simple class containing two strings, and a function to set the values
public class twoWords
{
public string word1 { get; set; }
public string word2 { get; set; }
public void setvalues(string words)
{
word1 = words.Substring(0,4);
word2 = words.Substring(5,4);
}
}
public class GOGO
{
public void ofCourseThisWillWorks()
{
//this is just to show that the setvalues function is working
twoWords twoWords = new twoWords();
twoWords.setvalues("word1 word2");
//tada. object twoWords is populated
}
public void thisdoesntwork()
{
//set up the test data to work with
List<string> stringlist = new List<string>();
stringlist.Add("word1 word2");
stringlist.Add("word3 word4");
//end setting up
//we want a list of class twoWords, contain two strings :
//word1 and word2. but i do not know how to call the setvalues function.
List<twoWords> twoWords = (from words in stringlist
select new twoWords().setvalues(words)).ToList();
}
}
Drugą funkcją GOGO
spowoduje błąd:
typ wyrażenia w klauzuli select jest niepoprawny. Wnioskowanie typu nie powiodło się w wywołaniu opcji "Wybierz".
Moje pytanie brzmi, jak mam wybrać nową twoWords
obiekt w powyższym from
klauzuli, podczas ustawiania wartości za pomocą funkcji setvalues
?
Odkładając to na bok, * naprawdę * ułatwia czytelność, jeśli będziesz przestrzegał konwencji nazewnictwa .NET nawet dla prostego kodu przykładowego . –