如何从Linq-Collection中提取字符串

时间:2013-12-20 12:38:12

标签: c# visual-studio-2010 linq lambda

我尝试从集合中提取单个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];

3 个答案:

答案 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期望函数返回boolx=>x.p.name返回string;因此错误信息。


您的代码的更直译是使用First而不是Single,因为如果找到多个元素,Single将抛出异常。

答案 1 :(得分:1)

您正在寻找以下内容:

Entity.Anzeige.Text.produkt = collection.Single().p.name;

注意:您的用法有点不一致 - Single()选择第一个元素,如果有多个,则抛出异常。如果您可能有2个以上的项目,请改用First()

答案 2 :(得分:0)

Entity.Anzeige.Text.produkt = collection.First().p.Name;