我尝试从集合中提取单个String。我的代码到目前为止工作,但我想将最后一部分缩短为一行,如我的例子所示:
private static void QueryText(Guid g)
{
var collection = from produkt in Entity.Memory.mProduktCollection.mProdColl
let p = produkt as Entity.Base.Produkt
from version in p.version
let v = version as Entity.Base.Version
from customer in v.customerCollection
let c = customer as Entity.Base.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Base.Fehler
select new { c, p, v, f };
collection = collection.Where(x => x.f.id == g);
List<string> lp = new List<string>();
lp.AddRange(collection.Select(x => x.p.name));
Entity.Anzeige.Text.produkt = lp[0];
}
实施例
类似的东西:
Entity.Anzeige.Text.produkt = collection.Single(x=>x.p.name);
它表示字符串无法转换为bool(但x.p.name是一个字符串!)
而不是:
List<string> lp = new List<string>();
lp.AddRange(collection.Select(x => x.p.name));
Entity.Anzeige.Text.produkt = lp[0];
答案 0 :(得分:4)
您可以省略Where
子句。而不是
collection = collection.Where(x => x.f.id == g);
List<string> lp = new List<string>();
lp.AddRange(collection.Select(x => x.p.name));
Entity.Anzeige.Text.produkt = lp[0];
只需使用
Entity.Anzeige.Text.produkt = collection.Single(x => x.f.id == g).p.name;
Entity.Anzeige.Text.produkt = collection.Single(x=>x.p.name);
它表示字符串无法转换为bool(但x.p.name是一个字符串!)
Single
期望函数返回bool
。 x=>x.p.name
返回string
;因此错误信息。
答案 1 :(得分:1)
您正在寻找以下内容:
Entity.Anzeige.Text.produkt = collection.Single().p.name;
注意:您的用法有点不一致 - Single()
选择第一个元素,如果有多个,则抛出异常。如果您可能有2个以上的项目,请改用First()
。
答案 2 :(得分:0)
Entity.Anzeige.Text.produkt = collection.First().p.Name;