直接从 linq 查询返回类

发布于 2024-11-09 17:32:47 字数 1294 浏览 3 评论 0原文

我还是 LINQ 新手。是否可以执行以下操作:

例如,我有一个类:

public class Person
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

现在我想通过读取 xml 文件的内容并返回它来将其作为类对象返回。

所以如果我读到这个 xml 文件:

<person>
    <firstname></firstname>
    <lastname></lastname>
</person>

读取 Person(假设这属于 People 类):

public static Person ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    var person = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  });
    return person as Person;
}

现在,如果我在其他地方执行以下操作:

Person p = new Person();
p = People.Person(xmlpath);
Response.Write(p.FirstName);

此处,p.FirstName 返回 null 异常。我的理解是因为 linq 查询返回了一个空类。

所以我的问题是,是否可以直接将内容添加到查询中的类中并返回它而不运行 foreach 循环并手动添加所有内容? (如下所示:)

Person p = new Person();
foreach (var x in person)
{
    p.FirstName = x.FirstName;
    p.LastName = x.LastName;
}

抱歉,如果这是一个愚蠢的问题。

谢谢

I'm still new to LINQ. Is it possible to do the following:

e.g., I have a class:

public class Person
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

Now i want to return it as a class object by reading, say, an xml file's contents and returning it.

So if i read this
xml file:

<person>
    <firstname></firstname>
    <lastname></lastname>
</person>

Read Person (say this belongs to a People class):

public static Person ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    var person = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  });
    return person as Person;
}

Now if i do the following elsewhere:

Person p = new Person();
p = People.Person(xmlpath);
Response.Write(p.FirstName);

Here, p.FirstName returns a null exception. Which i understand is because the linq query returned an empty class.

So my question is, is there anyway to directly add stuff into a class within a query and return it WITHOUT running a foreach loop and adding everything in manually? (like the following:)

Person p = new Person();
foreach (var x in person)
{
    p.FirstName = x.FirstName;
    p.LastName = x.LastName;
}

Sorry if this is a stupid question.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深居我梦 2024-11-16 17:32:47

您需要区分读取序列项目和读取单个项目。目前,ReadPerson 中的 person 变量实际上是 IEnumerable 类型 - 您将 person 作为 Person 返回它将为 null,因为该序列实际上不是 Person 的实例。如果您使用强制转换而不是 as,那么您之前就会看到这一点 - 但您必须对类型执行任何操作这一事实应该是一个警告你没有做正确的事。

我怀疑您实际上想要这个:

public static IEnumerable<Person> ReadPeople(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    return from p in xd.Descendants("person")
           select new Person
           {
               FirstName = p.Element("firstname").value,
               LastName = p.Element("lastname").value
           });
}

或这个:

public static Person ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    XElement element = xd.Descendants("person").First();
    return new Person
           {
               FirstName = element.Element("firstname").value,
               LastName = element.Element("lastname").value
           });
}

您还应该考虑如果有没有 person 元素或多个,您希望发生什么人物元素。 FirstFirstOrDefaultSingleSingleOrDefault 方法在这里对您很有用。

You need to distinguish between reading a sequence of items and reading a single item. Currently the person variable in ReadPerson is actually of type IEnumerable<Person> - you're returning person as Person which will be null, because that sequence isn't actually an instance of Person. If you'd used a cast instead of as, you'd have seen that earlier - but the very fact that you had to do anything to the types should be a warning that you weren't quite doing the right thing.

I suspect you actually want either this:

public static IEnumerable<Person> ReadPeople(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    return from p in xd.Descendants("person")
           select new Person
           {
               FirstName = p.Element("firstname").value,
               LastName = p.Element("lastname").value
           });
}

or this:

public static Person ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    XElement element = xd.Descendants("person").First();
    return new Person
           {
               FirstName = element.Element("firstname").value,
               LastName = element.Element("lastname").value
           });
}

You should also consider what you want to happen if there are no person elements, or multiple person elements. The First, FirstOrDefault, Single and SingleOrDefault methods will be useful for you here.

尹雨沫 2024-11-16 17:32:47

从我的阅读方式来看,您需要的是:

public static IEnumerable<Person> ReadPeople(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    return (from p in xd.Descendants("person")
            select new Person
            {
                FirstName = (string)p.Element("firstname"),
                LastName = (string)p.Element("lastname")
            });
}

这解决了:

  • 返回多个后代的问题
  • 未指定名字/姓氏的问题

如果您只想只有一个,则 ,然后使用Single() / First() / SingleOrDefault() / FirstOrDefault()

From how I read it, all you need is:

public static IEnumerable<Person> ReadPeople(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    return (from p in xd.Descendants("person")
            select new Person
            {
                FirstName = (string)p.Element("firstname"),
                LastName = (string)p.Element("lastname")
            });
}

This addresses:

  • the issue of returning multiple descendants
  • the issue of firstname/lastname not being specified

if you intent there to only be one, then use Single() / First() / SingleOrDefault() / FirstOrDefault().

◇流星雨 2024-11-16 17:32:47

我看到问题了! ReadPerson 方法中的 person 不是 Person 类的实例,而是集合 (IEnumerable) 并强制转换为 Person > 返回null

I see the problem! person in ReadPerson method is not instance of Person class, but collection (IEnumerable<Person>) and casting to Person returns null.

ㄟ。诗瑗 2024-11-16 17:32:47

以下行存在无效转换问题。你应该让编译器来帮助你(参见我修改后的函数)。

return person as Person;

您应该返回一个人员列表,而不仅仅是一个人。如果您确定 xml 中只有一个人,则可以调用 Single() 而不是 ToList()。

public static List<Person> ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    /*var person = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  });*/
    List<Person> persons = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  }).ToList();
    return persons;
}

The following line has the invalid casting problem. You should let the compiler to help you (see my modified function).

return person as Person;

You should return a list of persons instead of just a single person. If you are sure that only one person is in the xml, you can call Single() instead of ToList().

public static List<Person> ReadPerson(xmlpath)
{
    XDocument xd = XDocument.Load(xmlpath);
    /*var person = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  });*/
    List<Person> persons = (from p in xd.Descendants("person")
                  select new Person
                  {
                      FirstName = p.Element("firstname").value,
                      LastName = p.Element("lastname").value
                  }).ToList();
    return persons;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文